aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java15
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration1707Task.java41
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationMsg.java56
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationOperationUtils.java139
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AddGroupUuid.java131
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AllowMultipleHeats.java144
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AppConfig.java602
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/DerivedFromAlignment.java232
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/GroupsAlignment.java201
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/MigrationCategory.java48
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/MigrationSubCategory.java36
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/ServiceMigration.java1515
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/VfcNamingAlignment.java184
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1607/CsarMigration.java93
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/TitanFixUtils.java384
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/ToscaArtifactsAlignment.java461
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/DataTypesUpdate.java428
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/Migration1702.java1406
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/DistributionStatusUpdate.java160
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707.java58
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707ArtifactUuidFix.java585
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707Config.java279
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707MissingInfoFix.java220
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707RelationsFix.java151
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707VnfFix.java120
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationTitanStrategy.java33
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationUtils.java47
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/RenameGraphPropertyKeys.java56
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaNamesUpdate.java388
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaTemplateRegeneration.java175
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/VfModulesPropertiesAdding.java257
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/CategoriesUtils.java45
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ComponentMigration.java132
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ConsumersMigration.java67
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/InvariantUUIDResolver.java61
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/JsonModelMigration.java112
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/MigrationByIdDerivedNodeTypeResolver.java43
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NodeTemplateMissingDataResolver.java353
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesMigration.java86
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesResolver.java101
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourceVersionMigration.java42
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourcesCategoriesMigration.java181
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceCategoriesMigration.java71
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceVersionMigration.java43
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServicesMigration.java180
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UserStatesMigration.java187
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UsersMigration.java78
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VFResourcesMigration.java79
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VersionMigration.java118
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilitiesMigrationService.java104
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilityRequirementMigrationService.java184
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledRequirementsMigrationService.java104
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/RequirementsCapabilitiesMigrationService.java111
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationConfigManager.java14
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfiguration.java12
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/executers/TopologyTemplateValidatorExecuter.java23
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/TopologyTemplateValidationTask.java3
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ArtifactValidationUtils.java18
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ArtifactsVertexResult.java30
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ServiceArtifactValidationTask.java2
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/VfArtifactValidationTask.java5
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/moduleJson/ModuleJsonTask.java95
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/ReportManager.java89
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/VertexResult.java30
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/main/EsToCassandraDataMigrationMenu.java2
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/main/MigrationMenu.java345
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/main/SdcSchemaFileImport.java4
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ValidationTool.java11
-rw-r--r--asdctool/src/main/resources/config/logback.xml24
-rw-r--r--asdctool/src/main/resources/scripts/dataMigration.sh56
-rw-r--r--asdctool/src/main/resources/scripts/dataMigration1607.sh33
-rw-r--r--asdctool/src/main/resources/scripts/dataMigration1610.sh41
-rw-r--r--asdctool/src/main/resources/scripts/dataMigration1702.sh35
-rw-r--r--asdctool/src/main/resources/scripts/dataMigration1707.sh35
-rw-r--r--asdctool/src/main/resources/scripts/validationTool.sh3
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java24
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java29
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java11
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java48
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java27
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java58
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java1
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java24
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java1
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java39
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java55
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java104
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java51
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java11
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java81
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java1
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java8
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java23
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java3
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java114
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java11
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java37
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java50
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java63
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java5
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java10
-rw-r--r--catalog-be/src/main/webapp/WEB-INF/web.xml7
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java2
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java23
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java1
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java37
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java34
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java31
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java19
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java1
-rw-r--r--catalog-fe/src/main/webapp/WEB-INF/web.xml8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java1
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java57
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java25
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java10
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java12
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementLifecycleOperation.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java43
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java32
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAttributeOperation.java71
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java130
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java32
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java152
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java50
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java44
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java61
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java41
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java20
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java56
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java46
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java29
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java75
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java141
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java78
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java7
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java32
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AllOperationsUtil.java56
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java572
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java461
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java1170
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java1038
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java5495
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java2964
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java848
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java1565
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java1199
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java198
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java1077
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java957
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java27
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java1419
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java3040
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java1289
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java47
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java107
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationMalformedDataLogger.java67
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java6
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaFunctions.java19
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverter.java130
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java13
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java1
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaConverterUtils.java13
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java18
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java102
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java81
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java513
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java127
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java359
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java27
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java1993
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java218
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java2250
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java953
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java884
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorTest.java81
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java57
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverterTest.java187
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverterTest.java16
-rw-r--r--catalog-ui/package.json2
-rw-r--r--catalog-ui/src/app/models.ts1
-rw-r--r--catalog-ui/src/app/models/modal.ts4
-rw-r--r--catalog-ui/src/app/models/server-error-response.ts84
-rw-r--r--catalog-ui/src/app/ng2/app.module.ts19
-rw-r--r--catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.ts2
-rw-r--r--catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.html2
-rw-r--r--catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.ts2
-rw-r--r--catalog-ui/src/app/ng2/components/loader/loader.component.html3
-rw-r--r--catalog-ui/src/app/ng2/components/loader/loader.component.less16
-rw-r--r--catalog-ui/src/app/ng2/components/loader/loader.component.ts66
-rw-r--r--catalog-ui/src/app/ng2/components/modal/error-message/error-message.component.html5
-rw-r--r--catalog-ui/src/app/ng2/components/modal/error-message/error-message.component.ts (renamed from asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationException.java)17
-rw-r--r--catalog-ui/src/app/ng2/components/modal/modal.component.html8
-rw-r--r--catalog-ui/src/app/ng2/components/modal/modal.component.less15
-rw-r--r--catalog-ui/src/app/ng2/components/modal/modal.component.ts6
-rw-r--r--catalog-ui/src/app/ng2/components/modal/modal.module.ts9
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.html4
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.ts22
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/properties-table.component.html2
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.module.ts3
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html2
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less15
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts24
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties.utils.ts4
-rw-r--r--catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts4
-rw-r--r--catalog-ui/src/app/ng2/services/component-services/component.service.ts8
-rw-r--r--catalog-ui/src/app/ng2/services/component-services/service.service.ts4
-rw-r--r--catalog-ui/src/app/ng2/services/data-type.service.ts2
-rw-r--r--catalog-ui/src/app/ng2/services/http.interceptor.service.ts162
-rw-r--r--catalog-ui/src/app/ng2/services/http.service.ts29
-rw-r--r--catalog-ui/src/app/ng2/services/modal.service.ts27
-rw-r--r--catalog-ui/src/app/services/event-listener-service.ts2
-rw-r--r--catalog-ui/src/app/utils/constants.ts6
-rw-r--r--catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts3
-rw-r--r--catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts10
-rw-r--r--catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view.html2
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view-model.ts7
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts3
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view-model.ts225
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view.html5
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts10
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html3
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts1
-rw-r--r--catalog-ui/src/app/view-models/workspace/workspace-view-model.ts10
-rw-r--r--catalog-ui/src/assets/styles/app.less2
-rw-r--r--catalog-ui/src/assets/styles/sdc-ui.css361
-rw-r--r--catalog-ui/src/index.html2
-rw-r--r--catalog-ui/src/third-party/PunchOutRegistry.js27
-rw-r--r--catalog-ui/src/third-party/cytoscape.js-edge-editation/CytoscapeEdgeEditation.js3
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java13
-rw-r--r--openecomp-ui/external-resources/healthcheck/healthcheck (renamed from openecomp-ui/external-resources/healthcheck/v1.0/healthcheck)4
-rw-r--r--openecomp-ui/gulpfile.js17
-rw-r--r--openecomp-ui/pom.xml16
-rw-r--r--sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default/keystorebin0 -> 1416 bytes
-rw-r--r--sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_1_cleanup_jettydir.rb1
-rw-r--r--sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_2_setup_configuration.rb (renamed from sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_setup_configuration.rb)24
-rw-r--r--sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_jetty_Modules.rb (renamed from sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_2_locate_wars.rb)11
-rw-r--r--sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb38
-rw-r--r--sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-onboarding-configuration.yaml.erb5
-rw-r--r--sdc-os-chef/sdc-backend/chef-solo/roles/catalog-be.json4
-rw-r--r--sdc-os-chef/sdc-backend/startup.sh2
-rw-r--r--sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/files/default/keystorebin0 -> 1416 bytes
-rw-r--r--sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_1_cleanup_jettydir.rb8
-rw-r--r--sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_2_setup_configuration.rb17
-rw-r--r--sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_7_locate_keystore.rb16
-rw-r--r--sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-configuration.yaml.erb1
-rw-r--r--sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-onboarding-configuration.yaml.erb5
-rw-r--r--sdc-os-chef/sdc-frontend/chef-solo/roles/catalog-fe.json3
-rw-r--r--sdc-os-chef/sdc-frontend/startup.sh2
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/AndreyTest.java34
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java3
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java14
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java2006
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java3
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/VFCMTExternalAPI.java9
-rw-r--r--test-apis-ci/src/main/resources/ci/scripts/copyToStorage.sh13
-rw-r--r--test-apis-ci/src/main/resources/ci/testSuites/CRUDArtifacts.xml8
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Service_Tests_UI.java4
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CatalogLeftPanelTest.java11
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CustomizationUUID.java11
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/DeploymentViewTests.java12
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportDCAE.java40
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportVFCAsset.java12
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Onboard.java188
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java20
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Product.java18
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java12
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java10
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java14
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfArtifacts.java6
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java191
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/DriverFactory.java4
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java17
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java2
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java41
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java1
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java5
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java6
-rw-r--r--ui-ci/src/main/resources/ci/conf/attsdc.yaml13
-rw-r--r--ui-ci/src/main/resources/ci/scripts/copyToStorage.sh12
-rw-r--r--ui-ci/src/main/resources/ci/testSuites/extendedSanity.xml2
-rw-r--r--ui-ci/src/main/resources/ci/testSuites/onboardingVNFs.xml10
-rw-r--r--ui-ci/src/main/resources/ci/testSuites/onboardingVNFsShortFlow.xml18
298 files changed, 3378 insertions, 46848 deletions
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java
index abbaa3050d..d3ff8b7957 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java
@@ -20,13 +20,6 @@
package org.openecomp.sdc.ci.tests.execute.artifacts;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
import org.junit.Rule;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
@@ -34,7 +27,6 @@ import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.impl.AllOperationsUtil;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
@@ -53,6 +45,13 @@ import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.yaml.snakeyaml.Yaml;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
public class ValidateArtResponse extends ComponentBaseTest {
@Rule
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration1707Task.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration1707Task.java
deleted file mode 100644
index 2c19c94cff..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/Migration1707Task.java
+++ /dev/null
@@ -1,41 +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.migration;
-
-/**
- * for 1707 migration only!!!
- * please don't implement this interface unless you are sure you want to run with 1707 migration classes
- */
-public interface Migration1707Task {
-
- /**
- * performs a migration operation
- * @return true if migration completed successfully or false otherwise
- */
- boolean migrate();
-
- /**
- *
- * @return a description of what this migration does
- */
- String description();
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationMsg.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationMsg.java
deleted file mode 100644
index e743e5387b..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationMsg.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.asdctool.impl.migration;
-
-public enum MigrationMsg {
- RENMAE_KEY_PROPERTIES_1707("renaming key properties"),
- KEY_PROPERTY_NOT_EXIST("key propery %s not exist"),
- RENAME_KEY_PROPERTY_FAILED("failed to rename key property %s"),
- FAILED_TO_RETRIEVE_GRAPH("failed to get graph %s"),
- PROPERTY_KEY_NOT_EXIST("property key %s not found."),
- FAILED_TO_RETRIEVE_NODES("failed to retrieve nodes from graph. error status: %s"),
- FAILED_TO_GET_NODE_FROM_GRAPH("failed to retrieve node from graph. error status : %s"),
- FAILED_TO_CREATE_NODE("failed to create node of type %s. reason: %s"),
- FAILED_TO_RETRIEVE_CATEGORIES("failed to retrieve categories. error status: %s"),
- FAILED_TO_RETRIEVE_CATEGORY("failed to retrieve category %s. error status: %s"),
- FAILED_TO_CREATE_SUB_CATEGORY("failed to create sub category %s of category %s. error status: %s"),
- FAILED_TO_CREATE_CATEGORY("failed to create category %s. error status: %s"),
- FAILED_TO_RETRIEVE_USER_STATES("failed to retrieve user %s states. error status: %s"),
- FAILED_TO_RETRIEVE_MIGRATION_USER_STATES("failed to retrieve migrating user %s states for deletion. error status: %s"),
- FAILED_TO_RETRIEVE_MIGRATION_USER("failed to retrieve migration user %s. error status: %s"),
- FAILED_TO_RETRIEVE_VERSION_RELATION("failed to retrieve version relation from component with id %s to component with id %s. error status: %s"),
- FAILED_TO_RETRIEVE_REQ_CAP("failed to retrieve fulfilled requirements or capabilities for instance %s. error status: %s"),
- FAILED_TO_RETRIEVE_VERTEX("failed to retrieve vertex with id: %s. error status: %s"),
- FAILED_TO_RETRIEVE_CAP_REQ_VERTEX("failed to retrieve capabilities or requirements vertex for component %s. error status: %s"),
- FAILED_TO_ASSOCIATE_CAP_REQ("failed to associate fulfilled capabilities or requirements for components %s. error status: %s"),
- FAILED_TO_RETRIEVE_TOSCA_DEF("failed to retrieve tosca definition for requirement or capability %s. error status %s"),
- ;
-
- private String message;
-
- MigrationMsg(String migrationDescription) {
- this.message = migrationDescription;
- }
-
- public String getMessage(String ... msgProperties) {
- return String.format(this.message, msgProperties);
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationOperationUtils.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationOperationUtils.java
deleted file mode 100644
index 7a34521d93..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationOperationUtils.java
+++ /dev/null
@@ -1,139 +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.migration;
-
-import com.thinkaurelius.titan.core.PropertyKey;
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanVertex;
-import com.thinkaurelius.titan.core.schema.TitanManagement;
-import fj.data.Either;
-import org.apache.tinkerpop.gremlin.structure.VertexProperty;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import java.util.Map;
-import java.util.Optional;
-
-@Component("migrationUtils")
-public class MigrationOperationUtils {
-
- private static Logger log = LoggerFactory.getLogger(MigrationOperationUtils.class);
-
- @Autowired
- private TitanGenericDao titanGenericDao;
-
- /**
- * rename a set or property keys
- *
- * @param propertyKeys a mapping between the old property key name and the property key name to replace it with
- *
- * @return true if rename ended successfully or false otherwise
- */
- public boolean renamePropertyKeys(Map<String, String> propertyKeys) {
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- return graph.either((titanGraph) -> renamePropertyKeys(titanGraph, propertyKeys),
- (titanOperationStatus) -> operationFailed(MigrationMsg.FAILED_TO_RETRIEVE_GRAPH.getMessage(titanOperationStatus.name())));
- }
-
- private boolean renamePropertyKeys(TitanGraph titanGraph, Map<String, String> propertyKeys) {
- try {
- for (Map.Entry<String, String> propertyKeyEntry : propertyKeys.entrySet()) {
- boolean renameSucceeded = renamePropertyKey(titanGraph, propertyKeyEntry);
- if (!renameSucceeded) {
- return false;
- }
- }
- return true;
- } catch (RuntimeException e) {
- log.error(e.getMessage(), e);
- return false;
- }
- }
-
- private Boolean renamePropertyKey(TitanGraph titanGraph, Map.Entry<String, String> propertyKeyEntry) {
- String renameFromKey = propertyKeyEntry.getKey();
- String renameToKey = propertyKeyEntry.getValue();
- log.info(String.format("renaming property key %s to %s", renameFromKey, renameToKey));
- return renameProperty(titanGraph, renameFromKey, renameToKey);
- }
-
- private Boolean renameProperty(TitanGraph titanGraph, String renameFromKey, String renameToKey) {
- if (titanGraph.containsPropertyKey(renameFromKey) && titanGraph.containsPropertyKey(renameToKey)) {//new property already exist, we cant rename to it we need to add new and remove old on every vertices which has the old one.
- return renamePropertyOnEachVertex(titanGraph, renameFromKey, renameToKey);
- }
- return renamePropertyOnGraphLevel(titanGraph, renameFromKey, renameToKey);
- }
-
- private Boolean renamePropertyOnGraphLevel(TitanGraph titanGraph, String renameFromKey, String renameToKey) {
- TitanManagement titanManagement = titanGraph.openManagement();
- return Optional.ofNullable(titanManagement.getPropertyKey(renameFromKey))
- .map(propertyKey -> renamePropertyOnGraph(titanManagement, propertyKey, renameToKey))
- .orElseGet(() -> {log.info(MigrationMsg.PROPERTY_KEY_NOT_EXIST.getMessage(renameFromKey)); return true;}) ;//if property key not exist rename is considered to be successful
- }
-
- private boolean renamePropertyOnEachVertex(TitanGraph graph, String oldKey, String newKey) {
- addNewPropertyKeyOnVertices(graph, oldKey, newKey);
- removeOldPropertyKeyFromGraph(graph, oldKey);
- graph.tx().commit();
- return true;
- }
-
- private void removeOldPropertyKeyFromGraph(TitanGraph graph, String oldKey) {
- graph.getPropertyKey(oldKey).remove();
- }
-
- private void addNewPropertyKeyOnVertices(TitanGraph graph, String oldKey, String newKey) {
- graph.query().has(oldKey).vertices().forEach(titanVertex -> {
- copyOldKeyValueAndDropKey(oldKey, newKey, (TitanVertex) titanVertex);
- });
- }
-
- private void copyOldKeyValueAndDropKey(String oldKey, String newKey, TitanVertex titanVertex) {
- VertexProperty<Object> oldProperty = titanVertex.property(oldKey);
- Object oldKeyValue = oldProperty.value();
-
- titanVertex.property(newKey, oldKeyValue);
- oldProperty.remove();
- }
-
- private boolean renamePropertyOnGraph(TitanManagement titanManagement, PropertyKey fromPropertyKey, String toKey) {
- try {
- titanManagement.changeName(fromPropertyKey, toKey);
- titanManagement.commit();
- return true;
- } catch (RuntimeException e) {
- log.error(MigrationMsg.RENAME_KEY_PROPERTY_FAILED.getMessage(fromPropertyKey.name()), e.getMessage());
- titanManagement.rollback();
- return false;
- }
- }
-
- private boolean operationFailed(String errorMessage) {
- log.error(errorMessage);
- return false;
- }
-
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AddGroupUuid.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AddGroupUuid.java
deleted file mode 100644
index 03583fdfec..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AddGroupUuid.java
+++ /dev/null
@@ -1,131 +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.migration.v1604;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
-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.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.resources.data.GroupData;
-import org.slf4j.Logger;
-
-import fj.data.Either;
-
-public class AddGroupUuid {
-
- public static boolean addGroupUuids(TitanGenericDao titanGenericDao, Logger log, boolean inTrsansaction) {
-
- boolean result = true;
-
- try {
-
- log.debug("========================================================");
- log.debug("Before find all groups");
-
- Either<List<GroupData>, TitanOperationStatus> allGroups = titanGenericDao.getByCriteria(NodeTypeEnum.Group,
- null, null, GroupData.class);
-
- if (allGroups.isRight()) {
- TitanOperationStatus status = allGroups.right().value();
- log.debug("After finding all groups. Status is {}", status);
- if (status != TitanOperationStatus.NOT_FOUND && status != TitanOperationStatus.OK) {
- result = false;
- return result;
- } else {
- return result;
- }
- }
-
- List<GroupData> groups = allGroups.left().value();
-
- log.info("The number of groups fetched is {}", groups == null ? 0 : groups.size());
-
- int numberOfUpdates = 0;
- if (false == groups.isEmpty()) {
- Map<String, List<GroupData>> invariantIdToGroups = groups.stream()
- .collect(Collectors.groupingBy(p -> p.getGroupDataDefinition().getInvariantUUID()));
-
- // All the groups with the same invariantUUID should have the
- // same group UUID since update VF flow with CSAR was not
- // supported in the E2E environment.
-
- log.info("The number of different invariantUuids is {}",
- invariantIdToGroups == null ? 0 : invariantIdToGroups.size());
-
- for (Entry<String, List<GroupData>> entry : invariantIdToGroups.entrySet()) {
-
- String invariantUuid = entry.getKey();
- List<GroupData> groupsData = entry.getValue();
-
- StringBuilder builder = new StringBuilder();
- groupsData.forEach(p -> builder.append(p.getGroupDataDefinition().getUniqueId() + ","));
-
- String groupUUID = groupsData.get(0).getGroupDataDefinition().getGroupUUID();
-
- if (groupUUID == null) {
-
- groupUUID = UniqueIdBuilder.generateUUID();
-
- log.debug("Before updating groups {} with groupUUID {}",builder.toString(),groupUUID);
-
- for (GroupData groupData : groupsData) {
-
- numberOfUpdates++;
- groupData.getGroupDataDefinition().setGroupUUID(groupUUID);
- Either<GroupData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(groupData,
- GroupData.class);
- if (updateNode.isRight()) {
- log.error("Failed to update group {}. Error is {}",groupData,updateNode.right().value().toString());
- result = false;
- return result;
- }
-
- }
-
- log.debug("After updating groups {} with groupUUID {}",builder.toString(),groupUUID);
- }
-
- }
- }
-
- log.info("The number of groups updated with groupUUID is {}", numberOfUpdates);
-
- return result;
-
- } finally {
- log.info("Finish updating groupUUIDs. Status is {}.", result);
- if (inTrsansaction == false) {
- if (result == false) {
- titanGenericDao.rollback();
- } else {
- titanGenericDao.commit();
- }
- }
- }
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AllowMultipleHeats.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AllowMultipleHeats.java
deleted file mode 100644
index 3c9d6fa08f..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AllowMultipleHeats.java
+++ /dev/null
@@ -1,144 +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.migration.v1604;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-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.resources.data.ArtifactData;
-import org.slf4j.Logger;
-
-import fj.data.Either;
-
-public class AllowMultipleHeats {
-
- public static boolean removeAndUpdateHeatPlaceHolders(TitanGenericDao titanGenericDao, Logger log,
- boolean inTrsansaction) {
-
- boolean result = true;
-
- try {
-
- List<ArtifactData> artifactsToDelete = new ArrayList<>();
- List<ArtifactData> artifactsToUpdate = new ArrayList<>();
-
- String[] phLabels = { "heat", "heatvol", "heatnet" };
-
- for (String artifactLabel : phLabels) {
- Map<String, Object> properties = new HashMap<>();
-
- properties.put(GraphPropertiesDictionary.ARTIFACT_LABEL.getProperty(), artifactLabel);
-
- Either<List<ArtifactData>, TitanOperationStatus> allHeatArtifacts = titanGenericDao
- .getByCriteria(NodeTypeEnum.ArtifactRef, properties, null, ArtifactData.class);
-
- if (allHeatArtifacts.isRight()) {
- TitanOperationStatus status = allHeatArtifacts.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- continue;
- } else {
- result = false;
- return result;
- }
-
- }
-
- List<ArtifactData> list = allHeatArtifacts.left().value();
- log.debug("Found {} artifacts with label {}",(list == null ? 0 : list.size()),artifactLabel);
-
- if (list != null && false == list.isEmpty()) {
-
- for (ArtifactData artifactData : list) {
- String esId = artifactData.getArtifactDataDefinition().getEsId();
- if (esId == null || true == esId.isEmpty()) {
- artifactsToDelete.add(artifactData);
- } else {
- artifactsToUpdate.add(artifactData);
- }
- }
- }
- }
-
- if (false == artifactsToDelete.isEmpty()) {
- for (ArtifactData artifactData : artifactsToDelete) {
- // System.out.println("Going to delete artifact " +
- // artifactData);
- log.debug("Going to delete artifact {}",artifactData);
- Either<ArtifactData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(artifactData,
- ArtifactData.class);
- if (deleteNode.isRight()) {
- log.error("Failed to delete artifact node {}", deleteNode.left().value());
- result = false;
- return result;
- } else {
- log.debug("Delete artifact node {}",deleteNode.left().value());
- }
- }
- }
-
- log.debug("Number of deleted artifacts is {}",artifactsToDelete.size());
-
- int counter = 0;
- if (false == artifactsToUpdate.isEmpty()) {
- for (ArtifactData artifactData : artifactsToUpdate) {
- // System.out.println("Going to update artifact " +
- // artifactData);
-
- if (artifactData.getArtifactDataDefinition().getMandatory() != null
- && true == artifactData.getArtifactDataDefinition().getMandatory()) {
- log.debug("Going to update artifact {}",artifactData);
- counter++;
- artifactData.getArtifactDataDefinition().setMandatory(false);
- Either<ArtifactData, TitanOperationStatus> updatedNode = titanGenericDao
- .updateNode(artifactData, ArtifactData.class);
- if (updatedNode.isRight()) {
- log.error("Failed to update artifact node {}", updatedNode.left().value());
- result = false;
- return result;
- } else {
- log.debug("Update artifact node {}",updatedNode.left().value());
- }
- }
- }
- }
-
- log.debug("Number of updated artifacts is {}",counter);
-
- return result;
-
- } finally {
- if (inTrsansaction == false) {
- if (result == false) {
- titanGenericDao.rollback();
- } else {
- titanGenericDao.commit();
- }
- }
- }
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AppConfig.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AppConfig.java
deleted file mode 100644
index 3218ed262e..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/AppConfig.java
+++ /dev/null
@@ -1,602 +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.migration.v1604;
-
-import org.openecomp.sdc.asdctool.impl.PopulateComponentCache;
-import org.openecomp.sdc.asdctool.impl.migration.MigrationOperationUtils;
-import org.openecomp.sdc.asdctool.impl.migration.v1607.CsarMigration;
-import org.openecomp.sdc.asdctool.impl.migration.v1610.TitanFixUtils;
-import org.openecomp.sdc.asdctool.impl.migration.v1610.ToscaArtifactsAlignment;
-import org.openecomp.sdc.asdctool.impl.migration.v1702.DataTypesUpdate;
-import org.openecomp.sdc.asdctool.impl.migration.v1702.Migration1702;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.Migration1707ArtifactUuidFix;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.Migration1707RelationsFix;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.Migration1707VnfFix;
-import org.openecomp.sdc.be.auditing.api.IAuditingManager;
-import org.openecomp.sdc.be.auditing.impl.AuditingManager;
-import org.openecomp.sdc.be.components.ArtifactsResolver;
-import org.openecomp.sdc.be.components.distribution.engine.IDistributionEngine;
-import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder;
-import org.openecomp.sdc.be.components.impl.*;
-import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
-import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
-import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
-import org.openecomp.sdc.be.dao.cassandra.CassandraClient;
-import org.openecomp.sdc.be.dao.cassandra.ComponentCassandraDao;
-import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao;
-import org.openecomp.sdc.be.dao.config.DAOSpringConfig;
-import org.openecomp.sdc.be.dao.es.ElasticSearchClient;
-import org.openecomp.sdc.be.dao.impl.AuditingDao;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
-import org.openecomp.sdc.be.model.cache.ComponentCache;
-import org.openecomp.sdc.be.model.jsontitan.operations.GroupsOperation;
-import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation;
-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.IUserAdminOperation;
-import org.openecomp.sdc.be.model.operations.impl.AdditionalInformationOperation;
-import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation;
-import org.openecomp.sdc.be.model.operations.impl.AttributeOperation;
-import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityInstanceOperation;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ConsumerOperation;
-import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
-import org.openecomp.sdc.be.model.operations.impl.ElementOperation;
-import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
-import org.openecomp.sdc.be.model.operations.impl.GroupInstanceOperation;
-import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
-import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.HeatParametersOperation;
-import org.openecomp.sdc.be.model.operations.impl.InputsOperation;
-import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
-import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation;
-import org.openecomp.sdc.be.model.operations.impl.OnboardingClient;
-import org.openecomp.sdc.be.model.operations.impl.ProductOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.model.operations.impl.RequirementOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
-import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation;
-import org.openecomp.sdc.be.tosca.CsarUtils;
-import org.openecomp.sdc.be.tosca.ToscaExportHandler;
-import org.openecomp.sdc.be.user.IUserBusinessLogic;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Import;
-import org.springframework.context.annotation.Primary;
-
-@Configuration
-@Import(DAOSpringConfig.class)
-public class AppConfig {
-
- @Bean(name="artifact-resolver")
- public ArtifactsResolver artifactsResolver() {
- return new ArtifactResolverImpl();
- }
-
- @Bean(name = "sdc-schema-files-cassandra-dao")
- public SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao() {
- return new SdcSchemaFilesCassandraDao();
- }
- @Bean(name = "componentsUtils")
- public ComponentsUtils componentsUtils() {
- return new ComponentsUtils();
- }
- @Bean(name = "updateDataTypes")
- public DataTypesUpdate dataTypesUpdate() {
- return new DataTypesUpdate();
- }
- @Bean(name = "serviceMigrationBean")
- public ServiceMigration serviceMigration() {
- return new ServiceMigration();
- }
-
- @Bean(name = "vfcNamingAlignmentBean")
- public VfcNamingAlignment vfcNamingAlignment() {
- return new VfcNamingAlignment();
- }
-
- @Bean(name = "derivedFromAlignment")
- public DerivedFromAlignment derivedFromAlignment() {
- return new DerivedFromAlignment();
- }
-
- @Bean(name = "groupsAlignment")
- public GroupsAlignment groupsAlignment() {
- return new GroupsAlignment();
- }
-
- @Bean(name = "csarMigration")
- public CsarMigration csarMigration() {
- return new CsarMigration();
- }
-
- @Bean(name = "resource-operation")
- public ResourceOperation resourceOperation() {
- return new ResourceOperation();
- }
-
- @Bean(name = "service-operation")
- public ServiceOperation serviceOperation() {
- return new ServiceOperation();
- }
-
- @Bean(name = "component-instance-operation")
- public ComponentInstanceOperation componentInstanceOperation() {
- return new ComponentInstanceOperation();
- }
-
- @Bean(name = "capability-instanceOperation")
- public CapabilityInstanceOperation capabilityInstanceOperation() {
- return new CapabilityInstanceOperation();
- }
-
- @Bean(name = "property-operation")
- @Primary
- public PropertyOperation propertyOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
- return new PropertyOperation(titanGenericDao);
- }
-
- @Bean(name = "attribute-operation")
- public AttributeOperation attribueOperation() {
- return new AttributeOperation();
- }
-
- @Bean(name = "application-datatype-cache")
- public ApplicationDataTypeCache applicationDataTypeCache() {
- return new ApplicationDataTypeCache();
- }
-
- @Bean(name = "requirement-operation")
- public RequirementOperation requirementOperation() {
- return new RequirementOperation();
- }
-
- @Bean(name = "capability-operation")
- public CapabilityOperation capabilityOperation() {
- return new CapabilityOperation();
- }
-
- @Bean(name = "interface-operation")
- public InterfaceLifecycleOperation interfaceLifecycleOperation() {
- return new InterfaceLifecycleOperation();
- }
-
- @Bean(name = "element-operation")
- @Primary
- public IElementOperation elementOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
- return new ElementOperation(titanGenericDao);
- }
-
- @Bean(name = "additional-information-operation")
- public IAdditionalInformationOperation addioAdditionalInformationOperation() {
- return new AdditionalInformationOperation();
- }
-
- @Bean(name = "capability-type-operation")
- public CapabilityTypeOperation capabilityTypeOperation() {
- return new CapabilityTypeOperation();
- }
-
- @Bean(name = "artifact-operation")
- public ArtifactOperation artifactOperation() {
- return new ArtifactOperation();
- }
-
- @Bean(name = "heat-parameter-operation")
- public HeatParametersOperation heatParametersOperation() {
- return new HeatParametersOperation();
- }
-
- @Bean(name = "product-operation")
- public ProductOperation productOperation() {
- return new ProductOperation();
- }
-
- @Bean(name = "lifecycle-operation")
- public LifecycleOperation lifecycleOperation() {
- return new LifecycleOperation();
- }
-
- @Bean(name = "group-operation")
- public GroupOperation groupOperation() {
- return new GroupOperation();
- }
-
- @Bean(name = "groups-operation")
- public GroupsOperation jsonGroupsOperation() {
- return new GroupsOperation();
- }
-
- @Bean(name = "group-instance-operation")
- public GroupInstanceOperation groupInstanceOperation() {
- return new GroupInstanceOperation();
- }
-
- @Bean(name = "group-type-operation")
- @Primary
- public GroupTypeOperation groupTypeOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenricDao, @Qualifier("property-operation")PropertyOperation propertyOperation) {
- return new GroupTypeOperation(titanGenricDao, propertyOperation);
- }
-
- @Bean(name = "attribute-operation")
- public AttributeOperation attributeOperation() {
- return new AttributeOperation();
- }
-
- @Bean(name = "titanFixUtils")
- public TitanFixUtils titanFixUtils() {
- return new TitanFixUtils();
- }
-
- @Bean(name = "populateComponentCache")
- public PopulateComponentCache populateComponentCache() {
- return new PopulateComponentCache();
- }
-
- @Bean(name = "artifact-cassandra-dao")
- public ArtifactCassandraDao artifactCassandraDao() {
- return new ArtifactCassandraDao();
- }
-
- @Bean(name = "component-cassandra-dao")
- public ComponentCassandraDao componentCassandraDao() {
- return new ComponentCassandraDao();
- }
-
- @Bean(name = "cassandra-client")
- public CassandraClient cassandraClient() {
- return new CassandraClient();
- }
-
- @Bean(name = "cacheManger-operation")
- public CacheMangerOperation cacheMangerOperation() {
- return new CacheMangerOperation();
- }
-
- @Bean(name = "component-cache")
- public ComponentCache componentCache() {
- return new ComponentCache();
- }
-
- @Bean(name = "input-operation")
- public InputsOperation inputsOperation() {
- return new InputsOperation();
- }
-
- /**
- * Returns new instance of AuditCassandraDao
- *
- * @return
- */
- @Bean(name = "audit-cassandra-dao")
- public AuditCassandraDao auditCassandraDao() {
- return new AuditCassandraDao();
- }
-
- /**
- * Returns new instance of UserBusinessLogic
- *
- * @return
- */
- @Bean(name = "userBusinessLogic")
- public IUserBusinessLogic userBusinessLogic() {
- return new UserBusinessLogic();
- }
-
- /**
- * Returns new instance of UserAdminOperation
- *
- * @return
- */
- @Bean(name = "user-operation")
- @Primary
- public IUserAdminOperation userOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
- return new UserAdminOperation(titanGenericDao);
- }
-
- /**
- * Returns new instance of GraphLockOperation
- *
- * @return
- */
- @Bean(name = "graph-lock-operation")
- public IGraphLockOperation graphLockOperation() {
- return new GraphLockOperation();
- }
-
- /**
- * Returns new instance of AuditingDao
- *
- * @return
- */
- @Bean(name = "auditingDao")
- public AuditingDao auditingDao() {
- return new AuditingDao();
- }
-
- /**
- * Returns new instance of AuditingManager
- *
- * @return
- */
- @Bean(name = "auditingManager")
- public IAuditingManager auditingManager() {
- return new AuditingManager();
- }
-
- /**
- * Returns new instance of ServiceBusinessLogic
- *
- * @return
- */
- @Bean(name = "serviceBusinessLogic")
- public ServiceBusinessLogic serviceBusinessLogic() {
- return new ServiceBusinessLogic();
- }
-
- /**
- * Returns new instance of ComponentsUtils
- *
- * @return
- */
- @Bean(name = "componentUtils")
- public ComponentsUtils componentUtils() {
- return new ComponentsUtils();
- }
-
- /**
- * Returns new instance of ToscaArtifactsAlignment
- *
- * @return
- */
- @Bean(name = "toscaArtifactsAlignment")
- public ToscaArtifactsAlignment toscaArtifactsAlignment() {
- return new ToscaArtifactsAlignment();
- }
-
- /**
- * Returns new instance of ArtifactsBusinessLogic
- *
- * @return
- */
- @Bean(name = "artifactBusinessLogic")
- public ArtifactsBusinessLogic artifactBusinessLogic() {
- return new ArtifactsBusinessLogic();
- }
-
- /**
- * Returns new instance of ResourceBusinessLogic
- *
- * @return
- */
- @Bean(name = "resourceBusinessLogic")
- public ResourceBusinessLogic resourceBusinessLogic() {
- return new ResourceBusinessLogic();
- }
-
- /**
- * Returns new instance of LifecycleBusinessLogic
- *
- * @return
- */
- @Bean(name = "lifecycleBusinessLogic")
- public LifecycleBusinessLogic lifecycleBusinessLogic() {
- return new LifecycleBusinessLogic();
- }
-
- /**
- * Returns new instance of ServiceDistributionArtifactsBuilder
- *
- * @return
- */
- @Bean(name = "serviceDistributionArtifactsBuilder")
- public ServiceDistributionArtifactsBuilder serviceDistributionArtifactsBuilder() {
- return new ServiceDistributionArtifactsBuilder();
- }
-
- /**
- * Returns new instance of DistributionEngine
- *
- * @return
- */
- @Bean(name = "distributionEngine")
- public IDistributionEngine distributionEngine() {
- // This dependency is needed for initializing context but is not used
- return null;
- }
-
- /**
- * Returns new instance of ElasticSearchClient
- *
- * @return
- */
- @Bean(name = "elasticsearch-client")
- public ElasticSearchClient elasticsearchClient() {
- // This dependency is needed for initializing context but is not used
- return null;
- }
-
- /**
- * Returns new instance of ProductBusinessLogic
- *
- * @return
- */
- @Bean(name = "productBusinessLogic")
- public ProductBusinessLogic productBusinessLogic() {
- return new ProductBusinessLogic();
- }
-
- /**
- * Returns new instance of ProductComponentInstanceBusinessLogic
- *
- * @return
- */
- @Bean(name = "productComponentInstanceBusinessLogic")
- public ProductComponentInstanceBusinessLogic productComponentInstanceBusinessLogic() {
- return new ProductComponentInstanceBusinessLogic();
- }
-
- /**
- * Returns new instance of ToscaExportHandler
- *
- * @return
- */
- @Bean(name = "tosca-export-handler")
- public ToscaExportHandler toscaExportHandler() {
- return new ToscaExportHandler();
- }
-
- /**
- * Returns new instance of CsarOperation
- *
- * @return
- */
- @Bean(name = "csar-operation")
- public CsarOperation csarOperation() {
- return new CsarOperation();
- }
-
- /**
- * Returns new instance of OnboardingClient
- *
- * @return
- */
- @Bean(name = "onboarding-client")
- public OnboardingClient onboardingClient() {
- return new OnboardingClient();
- }
-
- /**
- * Returns new instance of VFComponentInstanceBusinessLogic
- *
- * @return
- */
- @Bean(name = "vfComponentInstanceBusinessLogic")
- public VFComponentInstanceBusinessLogic vfComponentInstanceBusinessLogic() {
- return new VFComponentInstanceBusinessLogic();
- }
-
- /**
- * Returns new instance of ResourceImportManager
- *
- * @return
- */
- @Bean(name = "resourceImportManager")
- public ResourceImportManager resourceImportManager() {
- return new ResourceImportManager();
- }
-
- /**
- * Returns new instance of GroupBusinessLogic
- *
- * @return
- */
- @Bean(name = "groupBusinessLogic")
- public GroupBusinessLogic groupBusinessLogic() {
- return new GroupBusinessLogic();
- }
-
- /**
- * Returns new instance of InputsBusinessLogic
- *
- * @return
- */
- @Bean(name = "inputsBusinessLogic")
- public InputsBusinessLogic inputsBusinessLogic() {
- return new InputsBusinessLogic();
- }
-
- /**
- * Returns new instance of CompositionBusinessLogic
- *
- * @return
- */
- @Bean(name = "compositionBusinessLogic")
- public CompositionBusinessLogic compositionBusinessLogic() {
- return new CompositionBusinessLogic();
- }
-
- /**
- * Returns new instance of CsarUtils
- *
- * @return
- */
- @Bean(name = "csar-utils")
- public CsarUtils csarUtils() {
- return new CsarUtils();
- }
-
- /**
- * Returns new instance of ServiceComponentInstanceBusinessLogic
- *
- * @return
- */
- @Bean(name = "serviceComponentInstanceBusinessLogic")
- public ServiceComponentInstanceBusinessLogic serviceComponentInstanceBusinessLogic() {
- return new ServiceComponentInstanceBusinessLogic();
- }
- /**
- *
- * @return new instance of migration1702
- */
- @Bean(name = "migration1702")
- public Migration1702 migration1702() {
- return new Migration1702();
- }
-
-
- @Bean(name = "migrationUtils")
- public MigrationOperationUtils migrationUtils() {
- return new MigrationOperationUtils();
- }
-
- @Bean("consumer-operation")
- public ConsumerOperation consumerOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) {
- return new ConsumerOperation(titanGenericDao);
- }
-
- @Bean(name = "migration1707relationsFix")
- public Migration1707RelationsFix migration1707RelationsFix() {
- return new Migration1707RelationsFix();
- }
- @Bean(name = "migration1707vnfFix")
- public Migration1707VnfFix migration1707VnfFix() {
- return new Migration1707VnfFix();
- }
- @Bean(name = "migration1707UuidFix")
- public Migration1707ArtifactUuidFix migration1707ArtifactUuidFix() {
- return new Migration1707ArtifactUuidFix();
- }
-
-
-// @Bean(name = "migration1707relationsFix")
-// public Migration1707RelationsFix migration1707RelationsFix() {
-// return new Migration1707RelationsFix();
-// }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/DerivedFromAlignment.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/DerivedFromAlignment.java
deleted file mode 100644
index c1ddc4fee0..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/DerivedFromAlignment.java
+++ /dev/null
@@ -1,232 +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.migration.v1604;
-
-import java.io.BufferedReader;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import fj.data.Either;
-
-public class DerivedFromAlignment {
- private static Logger log = LoggerFactory.getLogger(VfcNamingAlignment.class.getName());
- private Map<String, String> newDerivedFromValuesHM = new HashMap<String, String>();
- @Autowired
- protected TitanGenericDao titanGenericDao;
-
- public boolean alignDerivedFrom1604(String appConfigDir, String dataInputFileDir) {
- log.debug("Started alignDerivedFrom1604 procedure..");
- boolean result = false;
- try {
- if (!getDerivedFromValuesFromFile(dataInputFileDir)) {
- log.error("Started alignDerivedFrom1604 procedure was failed. Missing data in the input data file.");
- return result;
- }
- result = changeDerivedFrom();
- } finally {
- if (!result) {
- titanGenericDao.rollback();
- log.debug("**********************************************");
- log.debug("alignDerivedFrom1604 procedure FAILED!!");
- log.debug("**********************************************");
- } else {
- titanGenericDao.commit();
- log.debug("**********************************************");
- log.debug("alignDerivedFrom1604 procedure ended successfully!");
- log.debug("**********************************************");
- }
- }
- return result;
- }
-
- private boolean changeDerivedFrom() {
- Map<String, ResourceMetadataData> resourcesHM = getLatestVersionsOfResources();
- if (resourcesHM == null)
- return false;
- Map<String, ResourceMetadataData> derivedFromResourcesHM = getLatestCertifiedVersionsOfDerivedFromResources();
- if (derivedFromResourcesHM == null)
- return false;
- return updateEdges(resourcesHM, derivedFromResourcesHM);
- }
-
- private boolean updateEdges(Map<String, ResourceMetadataData> resourcesHM,
- Map<String, ResourceMetadataData> derivedFromResourcesHM) {
- log.debug("Updating of Edges has been started..");
- for (Entry<String, ResourceMetadataData> pair : resourcesHM.entrySet()) {
- ResourceMetadataData curResource = pair.getValue();
- String uniqeID = (String) curResource.getUniqueId();
- Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentResourceRes = titanGenericDao
- .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqeID,
- GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class);
- if (parentResourceRes.isLeft()) {
- ImmutablePair<ResourceMetadataData, GraphEdge> value = parentResourceRes.left().value();
- ResourceMetadataData parentResourceData = value.getKey();
- log.debug("Deleting old relation..");
- Either<GraphRelation, TitanOperationStatus> deletingRelationRes = titanGenericDao
- .deleteRelation(curResource, parentResourceData, GraphEdgeLabels.DERIVED_FROM);
- if (deletingRelationRes.isRight()) {
- log.error("Couldn't delete relation from resource {} to resource {}, error: {}",
- curResource.getMetadataDataDefinition().getName(),
- parentResourceData.getMetadataDataDefinition().getName(),
- deletingRelationRes.right().value());
- return false;
- }
- ResourceMetadataData newDerivedFromResource = derivedFromResourcesHM.get(pair.getKey());
- Either<GraphRelation, TitanOperationStatus> creatingRelationRes = titanGenericDao
- .createRelation(curResource, newDerivedFromResource, GraphEdgeLabels.DERIVED_FROM, null);
- if (creatingRelationRes.isRight()) {
- log.error("Couldn't create relation from resource {} to resource {}, error: {}",
- curResource.getMetadataDataDefinition().getName(),
- newDerivedFromResource.getMetadataDataDefinition().getName(),
- creatingRelationRes.right().value());
- return false;
- }
- } else {
- log.error("Couldn't get derived from resource for child resource {}, error: {}", pair.getKey(),
- parentResourceRes.right().value());
- return false;
- }
- }
- return true;
- }
-
- private Map<String, ResourceMetadataData> getLatestCertifiedVersionsOfDerivedFromResources() {
- log.debug("Getting latest certified versions of derived from resources according input file");
- Map<String, ResourceMetadataData> resourcesHM = new HashMap<String, ResourceMetadataData>();
- Map<String, Object> props = null;
- for (Entry<String, String> pair : newDerivedFromValuesHM.entrySet()) {
- props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), pair.getValue());
- props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
- Either<List<ResourceMetadataData>, TitanOperationStatus> highestVersionResource = titanGenericDao
- .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
- if (highestVersionResource.isRight()) {
- log.error("Couldn't get resource {} from DB, error: {}", pair.getValue(),
- highestVersionResource.right().value());
- return null;
- }
- List<ResourceMetadataData> highestVersionResourceAL = highestVersionResource.left().value();
- if (highestVersionResourceAL == null) {
- log.error("Couldn't get resource {}. No resource found", pair.getValue());
- return null;
- }
- ResourceMetadataData resource = highestVersionResourceAL.get(0);
- String state = resource.getMetadataDataDefinition().getState();
- if (!state.equals(LifecycleStateEnum.CERTIFIED.name())) {
- log.error(
- "alignDerivedFrom1604 procedure FAILED!! Derived from resource {} is not certified. Please certify manually and repeat the procedure.",
- pair.getValue());
- return null;
- }
- resourcesHM.put(pair.getKey(), resource);
- }
- return resourcesHM;
- }
-
- private Map<String, ResourceMetadataData> getLatestVersionsOfResources() {
- log.debug("Getting latest versions of resources according input file");
- Map<String, ResourceMetadataData> resourcesHM = new HashMap<String, ResourceMetadataData>();
- ResourceMetadataData foundResource = null;
- Map<String, Object> props = null;
- for (Entry<String, String> pair : newDerivedFromValuesHM.entrySet()) {// filter
- props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), pair.getKey());
- props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> highestVersionResource = titanGenericDao
- .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
- if (highestVersionResource.isRight()) {
- log.error("Couldn't get resource {} from DB, error: {}", pair.getKey(),
- highestVersionResource.right().value());
- return null;
- }
- List<ResourceMetadataData> highestVersionResourceAL = highestVersionResource.left().value();
- if (highestVersionResourceAL == null) {
- log.error("Couldn't get resource {}. No resource found", pair.getKey());
- return null;
- }
- if (highestVersionResourceAL.size() > 2) {
- log.error("Invalid response. Found more than two highest version resources with name {}.",
- pair.getKey());
- return null;
- }
- foundResource = highestVersionResourceAL.get(0);
- if (highestVersionResourceAL.size() == 2) {
- foundResource = foundResource.getMetadataDataDefinition().getState()
- .equals(LifecycleStateEnum.CERTIFIED.name()) ? highestVersionResourceAL.get(1) : foundResource;
- }
- resourcesHM.put(pair.getKey(), foundResource);
- }
- return resourcesHM;
- }
-
- private boolean getDerivedFromValuesFromFile(String dataInputFileDir) {
- BufferedReader br = null;
- String curPair = null;
- try {
- br = new BufferedReader(new FileReader(dataInputFileDir));
- while ((curPair = br.readLine()) != null) {
- String[] pair = curPair.split(" ");
- if (pair.length < 2) {
- log.error(
- "Expected at least two tokens in every line. Usage: <resource_name> <new_derived_from_name>");
- return false;
- }
- String derivedFrom = pair[pair.length - 1];
- String name = curPair.substring(0, curPair.length() - derivedFrom.length() - 1);
- newDerivedFromValuesHM.put(name, derivedFrom);
- }
- return true;
- } catch (FileNotFoundException e) {
- log.error("Started alignDerivedFrom1604 procedure was failed. Missing input data file.", e);
- } catch (IOException e) {
- log.error("Started alignDerivedFrom1604 procedure was failed. The input data file is empty.", e);
- } finally {
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- log.debug("failed to close file reader", e);
- }
- }
- }
- return false;
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/GroupsAlignment.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/GroupsAlignment.java
deleted file mode 100644
index aebcddfee2..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/GroupsAlignment.java
+++ /dev/null
@@ -1,201 +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.migration.v1604;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-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.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupTypeDefinition;
-import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
-import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import fj.data.Either;
-
-public class GroupsAlignment {
-
- private static Logger log = LoggerFactory.getLogger(ServiceMigration.class.getName());
-
- public static String INITIAL_VERSION = "1.0";
- private static final String DEFAULT_GROUP_VF_MODULE = "org.openecomp.groups.VfModule";
- private static final String MODULE = "::module-";
-
- @Autowired
- protected TitanGenericDao titanGenericDao;
- @Autowired
- protected IArtifactOperation artifactOperation;
- @Autowired
- protected IGroupOperation groupOperation;
- @Autowired
- protected GroupTypeOperation groupTypeOperation;
-
- public boolean alignGroups(String appConfigDir) {
-
- log.debug("Started the align groups procedure ...");
- log.debug("Getting all resources with resources");
- boolean result = false;
- try {
-
- Map<String, Object> properties = new HashMap<>();
- properties.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
- Either<List<ResourceMetadataData>, TitanOperationStatus> allVfResources = titanGenericDao
- .getByCriteria(NodeTypeEnum.Resource, properties, ResourceMetadataData.class);
-
- if (allVfResources.isRight()) {
- log.error("Couldn't get VF resources from DB, error: {}", allVfResources.right().value());
- result = false;
- return result;
- }
- List<ResourceMetadataData> resourcesList = allVfResources.left().value();
- if (resourcesList == null) {
- log.error("Couldn't get VF resources from DB, no resources found");
- result = false;
- return result;
- }
- log.debug("Found {} VF resources", resourcesList.size());
- for (ResourceMetadataData resource : resourcesList) {
- result = createGroupIfContainsArtifacts(resource);
- }
- } finally {
- if (!result) {
- titanGenericDao.rollback();
- log.debug("**********************************************");
- log.debug("The align groups procedure FAILED!!");
- log.debug("**********************************************");
- } else {
- titanGenericDao.commit();
- log.debug("**********************************************");
- log.debug("The align groups procedure ended successfully!");
- log.debug("**********************************************");
- }
- }
-
- return result;
- }
-
- private boolean createGroupIfContainsArtifacts(ResourceMetadataData resource) {
-
- String uniqueId = resource.getMetadataDataDefinition().getUniqueId();
- StorageOperationStatus result = StorageOperationStatus.OK;
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> allArtifactsRes = artifactOperation
- .getArtifacts(uniqueId, NodeTypeEnum.Resource, true);
- if (allArtifactsRes.isRight()) {
- log.error("Couldn't get resource artifacts from DB, error: {}", allArtifactsRes.right().value());
- return false;
- }
- Map<String, ArtifactDefinition> artifactsHM = allArtifactsRes.left().value();
- ArrayList<String> foundArtifactsAL = new ArrayList<String>();
- for (ArtifactDefinition curArtifact : artifactsHM.values()) {
- String atrifactType = curArtifact.getArtifactType();
- if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())
- || atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType())
- || atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
- foundArtifactsAL.add(curArtifact.getUniqueId());
- }
- }
- if (foundArtifactsAL.size() > 0) {
- Either<List<GroupDefinition>, TitanOperationStatus> allGroupsRes = groupOperation
- .getAllGroupsFromGraph(uniqueId, NodeTypeEnum.Resource);
- int groupCounter = 1;
- if (allGroupsRes.isRight()) {
- if (allGroupsRes.right().value().name().equals(TitanOperationStatus.OK.name())
- || allGroupsRes.right().value().name().equals(TitanOperationStatus.NOT_FOUND.name())) {
- log.debug("Not found groups resource related to resource {}, response: {}",
- resource.getMetadataDataDefinition().getName(), allGroupsRes.right().value());
- } else {
- log.error("Not found groups resource related to resource {}, DB error: {}",
- resource.getMetadataDataDefinition().getName(), allGroupsRes.right().value());
- return false;
- }
- } else if (allGroupsRes.left().value() != null && allGroupsRes.left().value().size() > 0) {
- groupCounter += allGroupsRes.left().value().size();
- for (GroupDefinition curGroup : allGroupsRes.left().value()) {
- for (String curGroupArtifact : curGroup.getArtifacts()) {
- if (foundArtifactsAL.contains(curGroupArtifact)) {
- foundArtifactsAL.remove(curGroupArtifact);
- }
- }
- }
- }
- if (foundArtifactsAL.size() > 0) {
- GroupDefinition groupDefinition = new GroupDefinition();
- groupDefinition.setName(resource.getMetadataDataDefinition().getName() + MODULE + groupCounter);
- groupDefinition.setType(DEFAULT_GROUP_VF_MODULE);
- groupDefinition.setArtifacts(foundArtifactsAL);
- log.debug("Creating new group {} for VF resource {}", groupDefinition.getName(),
- resource.getMetadataDataDefinition().getName());
- return createGroup(resource.getUniqueId(), ComponentTypeEnum.RESOURCE, groupDefinition);
-
- }
- }
- return true;
- }
-
- private boolean createGroup(Object uniqueId, ComponentTypeEnum componentType, GroupDefinition groupDefinition) {
-
- NodeTypeEnum nodeTypeEnum = componentType.getNodeType();
- String groupType = groupDefinition.getType();
-
- Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeRes = groupTypeOperation
- .getLatestGroupTypeByType(groupType, true);
- if (getGroupTypeRes.isRight()) {
- log.error("Couldn't get grouptype by type {} from DB, error: {}", groupType,
- getGroupTypeRes.right().value());
- return false;
- }
-
- GroupTypeDefinition groupTypeDefinition = getGroupTypeRes.left().value();
-
- String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
- groupDefinition.setInvariantUUID(invariantUUID);
- groupDefinition.setVersion(INITIAL_VERSION);
- groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId());
-
- Either<GroupDefinition, StorageOperationStatus> addGroupToGraphRes = groupOperation.addGroup(nodeTypeEnum,
- (String) uniqueId, groupDefinition, true);
-
- if (addGroupToGraphRes.isRight()) {
- log.error("Couldn't add group {} to graph, error: {}", groupDefinition.getName(),
- addGroupToGraphRes.right().value());
- return false;
- }
- log.debug("The group {} has been created", groupDefinition.getName());
- return true;
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/MigrationCategory.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/MigrationCategory.java
deleted file mode 100644
index 5605f0980d..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/MigrationCategory.java
+++ /dev/null
@@ -1,48 +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.migration.v1604;
-
-import java.util.List;
-
-import org.openecomp.sdc.be.datatypes.category.CategoryDataDefinition;
-
-public class MigrationCategory extends CategoryDataDefinition {
- private String oldName;
-
- List<MigrationSubCategory> subcategories;
-
- public String getOldName() {
- return oldName;
- }
-
- public void setOldName(String oldName) {
- this.oldName = oldName;
- }
-
- public List<MigrationSubCategory> getSubcategories() {
- return subcategories;
- }
-
- public void setSubcategories(List<MigrationSubCategory> subcategories) {
- this.subcategories = subcategories;
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/MigrationSubCategory.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/MigrationSubCategory.java
deleted file mode 100644
index f1886622be..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/MigrationSubCategory.java
+++ /dev/null
@@ -1,36 +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.migration.v1604;
-
-import org.openecomp.sdc.be.datatypes.category.SubCategoryDataDefinition;
-
-public class MigrationSubCategory extends SubCategoryDataDefinition {
- private String oldName;
-
- public String getOldName() {
- return oldName;
- }
-
- public void setOldName(String oldName) {
- this.oldName = oldName;
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/ServiceMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/ServiceMigration.java
deleted file mode 100644
index 0ef435e1c3..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/ServiceMigration.java
+++ /dev/null
@@ -1,1515 +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.migration.v1604;
-
-import static java.nio.file.Files.readAllBytes;
-import static java.nio.file.Paths.get;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.UUID;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.tinkerpop.gremlin.structure.Direction;
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
-import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
-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.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-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.AdditionalInformationOperation;
-import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
-import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation;
-import org.openecomp.sdc.be.model.operations.impl.ProductOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.resources.data.CapabilityData;
-import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
-import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
-import org.openecomp.sdc.be.resources.data.ProductMetadataData;
-import org.openecomp.sdc.be.resources.data.RelationshipInstData;
-import org.openecomp.sdc.be.resources.data.RequirementData;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
-import org.openecomp.sdc.be.resources.data.TagData;
-import org.openecomp.sdc.be.resources.data.category.CategoryData;
-import org.openecomp.sdc.be.resources.data.category.SubCategoryData;
-import org.openecomp.sdc.be.utils.CommonBeUtils;
-import org.openecomp.sdc.common.util.ValidationUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.yaml.snakeyaml.Yaml;
-
-import com.thinkaurelius.titan.core.TitanEdge;
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-public class ServiceMigration {
-
- private static final String[] NORMATIVE_OLD_NAMES = { "tosca.nodes.network.Network", "tosca.nodes.network.Port", "tosca.nodes.BlockStorage", "tosca.nodes.Compute", "tosca.nodes.Container.Application", "tosca.nodes.Container.Runtime",
- "tosca.nodes.Database", "tosca.nodes.DBMS", "tosca.nodes.LoadBalancer", "tosca.nodes.ObjectStorage", "tosca.nodes.Root", "tosca.nodes.SoftwareComponent", "tosca.nodes.WebApplication", "tosca.nodes.WebServer", };
-
- private static Logger log = LoggerFactory.getLogger(ServiceMigration.class.getName());
-
- @Autowired
- protected TitanGenericDao titanGenericDao;
- @Autowired
- protected ResourceOperation resourceOperation;
- @Autowired
- protected ServiceOperation serviceOperation;
- @Autowired
- protected ProductOperation productOperation;
- @Autowired
- protected LifecycleOperation lifecycleOperaion;
- @Autowired
- protected PropertyOperation propertyOperation;
- @Autowired
- protected AdditionalInformationOperation additionalInformationOperation;
- @Autowired
- protected ComponentInstanceOperation componentInstanceOperaion;
- @Autowired
- protected IElementOperation elementOperation;
-
- public boolean migrate1602to1604(String appConfigDir) {
-
- boolean result = false;
-
- try {
-
- if (!addResourceCounterToResources()) {
- log.debug("Failed to update resource instance counter on resources");
- result = false;
- return result;
- }
- if (!updateComponentInstanceType()) {
- log.debug("Failed to update component instance type");
- result = false;
- return result;
- }
- // fix VF
- if (!fixDerivedVf()) {
- log.debug("Failed to fix VFs");
- result = false;
- return result;
- }
- // update instances and relation
- if (!updateCalculatedEdges()) {
- log.debug("Failed to update calculated edges for VF instances");
- result = false;
- return result;
- }
- // update instances and relation
- if (!updateRelations()) {
- log.debug("Failed to update Instance And Relations in services");
- result = false;
- return result;
- }
- if (!updateCategories(appConfigDir)) {
- log.debug("Failed to update categories");
- result = false;
- return result;
- }
-
- if (!AllowMultipleHeats.removeAndUpdateHeatPlaceHolders(titanGenericDao, log, true)) {
- log.error("Failed to update heat place holders");
- result = false;
- return result;
- }
-
- if (!AddGroupUuid.addGroupUuids(titanGenericDao, log, true)) {
- log.error("Failed to update group UUIDs");
- result = false;
- return result;
- }
-
- result = true;
- } finally {
- if (!result) {
- titanGenericDao.rollback();
- } else {
- titanGenericDao.commit();
- }
- }
- return result;
- }
-
- private boolean updateCategories(String appConfigDir) {
- // String categoryMigrationFile = appConfigDir + File.separator +
- // "categoryMigration.yaml";
- String categoryMigrationFile = appConfigDir + "categoryMigration.yaml";
-
- Map<String, List<MigrationCategory>> categoriesFromYml;
- try {
- categoriesFromYml = createCategoriesFromYml(categoryMigrationFile);
- if (categoriesFromYml == null || categoriesFromYml.isEmpty()) {
- log.debug("updateCategories failed to load categories form migration file {}", categoryMigrationFile);
- return false;
- }
- } catch (Exception e) {
- log.debug("Failed to load category migration file : {}", categoryMigrationFile, e);
- return false;
- }
- for (Map.Entry<String, List<MigrationCategory>> entry : categoriesFromYml.entrySet()) {
- ComponentTypeEnum componentType = ComponentTypeEnum.findByParamName(entry.getKey());
- if (componentType != null) {
- switch (componentType) {
- case RESOURCE:
- if (updateResourceCategories(entry.getValue()) == false) {
- log.debug("updateCategories failed to update resource categories");
- return false;
- }
- break;
- case SERVICE:
- if (updateServiceCategories(entry.getValue()) == false) {
- log.debug("updateCategories failed to update service categories");
- return false;
- }
- break;
- default:
- log.debug("updateCategories no changes for categories from type {}", componentType);
- }
- } else {
- log.debug("updateCategories failed not supported component file in migration categories file" + entry.getKey());
- return false;
- }
- }
- return true;
- }
-
- private boolean updateServiceCategories(List<MigrationCategory> categories) {
- log.debug("updateServiceCategories STARTED");
- Either<List<CategoryDefinition>, ActionStatus> serviceCategories = elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, true);
- if (serviceCategories.isRight()) {
- log.debug("updateServiceCategories failed fetch all service categories ,error " + serviceCategories.right().value());
- return false;
- }
- for (MigrationCategory newCat : categories) {
-
- if (newCat.getOldName() == null) {
- // add new
- boolean exist = false;
- for (CategoryDefinition catInDB : serviceCategories.left().value()) {
- if (newCat.getName().equals(catInDB.getName())) {
- exist = true;
- break;
- }
- }
- if (!exist) {
- CategoryDefinition categoryDefinition = new CategoryDefinition(newCat);
- Either<CategoryDefinition, ActionStatus> result = elementOperation.createCategory(categoryDefinition, NodeTypeEnum.ServiceNewCategory, true);
- if (result.isRight()) {
- log.debug("Failed to create service category {} error {}", categoryDefinition, result.right().value());
- return false;
- }
- log.debug("service category {} created", categoryDefinition);
- }
- } else {
- // update exist
- for (CategoryDefinition catInDB : serviceCategories.left().value()) {
- if (newCat.getOldName().equals(catInDB.getName())) {
- Either<CategoryData, TitanOperationStatus> updateSingleResult = updateSingleResourceCategory(newCat, NodeTypeEnum.ServiceNewCategory);
- if (updateSingleResult.isRight()) {
- return false;
- }
- break;
- }
- }
- }
- }
- log.debug("updateServiceCategories ENDED");
- return true;
- }
-
- private Either<CategoryData, TitanOperationStatus> updateSingleResourceCategory(MigrationCategory newCat, NodeTypeEnum nodetype) {
- Map<String, Object> properties = new HashMap<>();
- properties.put(GraphPropertiesDictionary.NAME.getProperty(), newCat.getOldName());
- Either<List<CategoryData>, TitanOperationStatus> categoryEither = titanGenericDao.getByCriteria(nodetype, properties, CategoryData.class);
- if (categoryEither.isRight() && categoryEither.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("Failed to get {} categories, for name {} error {}", nodetype, newCat.getOldName(), categoryEither.right().value());
- return Either.right(categoryEither.right().value());
- }
- List<CategoryData> categoryList = (categoryEither.isLeft() ? categoryEither.left().value() : null);
- if (categoryList == null) {
- log.debug("No {} categories, for name {} error {}", nodetype, newCat.getOldName());
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
- CategoryData categoryData = categoryList.get(0);
- categoryData.getCategoryDataDefinition().setName(newCat.getName());
- categoryData.getCategoryDataDefinition().setIcons(newCat.getIcons());
- categoryData.getCategoryDataDefinition().setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(newCat.getName()));
- Either<CategoryData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(categoryData, CategoryData.class);
- if (updateNode.isRight()) {
- log.debug("Failed to update {} category {} error {}", nodetype, categoryData, updateNode.right().value());
- return Either.right(updateNode.right().value());
- }
- log.debug("Update {} category {} ", nodetype, categoryData);
- return Either.left(updateNode.left().value());
- }
-
- private boolean updateResourceCategories(List<MigrationCategory> categories) {
- log.debug("updateResourceCategories STARTED");
- Either<List<CategoryDefinition>, ActionStatus> resourceCategories = elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, true);
- if (resourceCategories.isRight()) {
- log.debug("updateResourceCategories failed fetch all resource categories ,error " + resourceCategories.right().value());
- return false;
- }
- for (MigrationCategory newCat : categories) {
- if (newCat.getOldName() == null) {
- // add new
- // check if already created in previous running
- boolean exist = false;
- for (CategoryDefinition catInDB : resourceCategories.left().value()) {
- if (newCat.getName().equals(catInDB.getName())) {
- exist = true;
- }
- }
- if (!exist) {
- CategoryDefinition categoryDefinition = new CategoryDefinition(newCat);
- Either<CategoryDefinition, ActionStatus> resultCat = elementOperation.createCategory(categoryDefinition, NodeTypeEnum.ResourceNewCategory, true);
- if (resultCat.isRight()) {
- log.debug("Failed to create resource category {} error {}", categoryDefinition, resultCat.right().value());
- return false;
- }
- log.debug("resource category {} created", categoryDefinition);
-
- List<MigrationSubCategory> nSubCat = newCat.getSubcategories();
- List<MigrationSubCategory> newSubcat = nSubCat;
- List<MigrationSubCategory> subcategories = newSubcat;
- for (MigrationSubCategory msubcat : subcategories) {
- SubCategoryDefinition subcat = new SubCategoryDefinition(msubcat);
- Either<SubCategoryDefinition, ActionStatus> resultSubcat = elementOperation.createSubCategory(resultCat.left().value().getUniqueId(), subcat, NodeTypeEnum.ResourceSubcategory, true);
- if (resultSubcat.isRight()) {
- log.debug("Failed to create resource sub category {} error {}", subcat, resultSubcat.right().value());
- return false;
- }
- log.debug("resource sub category {} created for category {}", categoryDefinition, resultCat.left().value().getName());
- }
- }
- } else {
- // update exist
- for (CategoryDefinition catInDB : resourceCategories.left().value()) {
- if (newCat.getOldName().equals(catInDB.getName())) {
- Either<CategoryData, TitanOperationStatus> updateSingleResult = updateSingleResourceCategory(newCat, NodeTypeEnum.ResourceNewCategory);
- if (updateSingleResult.isRight()) {
- return false;
- }
-
- CategoryData categoryData = updateSingleResult.left().value();
- for (MigrationSubCategory migSubCat : newCat.getSubcategories()) {
- if (migSubCat.getOldName() == null) {
- // create new one
- boolean existSub = false;
- for (SubCategoryDefinition subCatInDb : catInDB.getSubcategories()) {
- if (subCatInDb.getName().equals(migSubCat.getName())) {
- existSub = true;
- }
- }
- if (!existSub) {
- SubCategoryDefinition subcat = new SubCategoryDefinition(migSubCat);
-
- Either<SubCategoryDefinition, ActionStatus> resultSubcat = elementOperation.createSubCategory((String) categoryData.getUniqueId(), subcat, NodeTypeEnum.ResourceSubcategory, true);
- if (resultSubcat.isRight()) {
- log.debug("Failed to create resource sub category {} error {}", subcat, resultSubcat.right().value());
- return false;
- }
- log.debug("resource sub category {} created for category {}", categoryData, resultSubcat.left().value().getName());
- }
- } else {
- if (updateSingleSubCategory(newCat, migSubCat, updateSingleResult.left().value()) == false) {
- return false;
- }
- }
- }
- break;
- }
- }
- }
- }
- return true;
- }
-
- private boolean updateSingleSubCategory(MigrationCategory newCat, MigrationSubCategory migSubCat, CategoryData categoryData) {
-
- Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> subcategories = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(),
- GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class);
-
- if (subcategories.isRight()) {
- log.debug("Failed to get resource sub categories, for name {} error {}", newCat.getOldName(), subcategories.right().value());
- return false;
- }
-
- for (ImmutablePair<SubCategoryData, GraphEdge> pair : subcategories.left().value()) {
- if (pair.getKey().getSubCategoryDataDefinition().getName().equals(migSubCat.getOldName())) {
- SubCategoryData subCategoryData = pair.getKey();
- subCategoryData.getSubCategoryDataDefinition().setName(migSubCat.getName());
- subCategoryData.getSubCategoryDataDefinition().setIcons(migSubCat.getIcons());
- subCategoryData.getSubCategoryDataDefinition().setNormalizedName(ValidationUtils.normalizeCategoryName4Uniqueness(migSubCat.getName()));
- Either<SubCategoryData, TitanOperationStatus> updateSubNode = titanGenericDao.updateNode(subCategoryData, SubCategoryData.class);
- if (updateSubNode.isRight()) {
- log.debug("Failed to update resource sub category {} error {}", subCategoryData, updateSubNode.right().value());
- return false;
- }
- log.debug("Update resource subcategory category {} ", subCategoryData);
- break;
- }
- }
- return true;
- }
-
- private Map<String, List<MigrationCategory>> createCategoriesFromYml(String categoriesTypesYml) {
- String yamlAsString;
- try {
- yamlAsString = new String(readAllBytes(get(categoriesTypesYml)));
- } catch (Exception e) {
- log.debug("Failed to load category import file exception : ", e);
- return null;
- }
-
- log.debug("received yaml: {}", yamlAsString);
-
- Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(yamlAsString);
- Map<String, List<MigrationCategory>> allCategories = new HashMap<>();
-
- Iterator<Entry<String, Object>> categoryEntryItr = toscaJson.entrySet().iterator();
- while (categoryEntryItr.hasNext()) {
- Entry<String, Object> categoryTypeEntry = categoryEntryItr.next();
- String categoryType = categoryTypeEntry.getKey();
- List<MigrationCategory> categoriesPerType = null;
- Map<String, Object> categoryPerType = null;
- switch (categoryType) {
- case ComponentTypeEnum.SERVICE_PARAM_NAME:
- categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue();
- categoriesPerType = createServiceCategories(categoryPerType);
- break;
- case ComponentTypeEnum.RESOURCE_PARAM_NAME:
- categoryPerType = (Map<String, Object>) categoryTypeEntry.getValue();
- categoriesPerType = createResourceCategories(categoryPerType);
- break;
- case ComponentTypeEnum.PRODUCT_PARAM_NAME:
- // TODO
- break;
- default:
- log.debug("Not supported category type - {}", categoryType);
- break;
- }
- if (categoriesPerType != null) {
- allCategories.put(categoryType, categoriesPerType);
- }
- }
- return allCategories;
- }
-
- private List<MigrationCategory> createServiceCategories(Map<String, Object> categories) {
- List<MigrationCategory> categroiesDef = new ArrayList<>();
- String catName = null;
- List<String> icons = null;
- String oldName = null;
- for (Entry<String, Object> entry : categories.entrySet()) {
- MigrationCategory catDef = new MigrationCategory();
- Map<String, Object> category = (Map<String, Object>) entry.getValue();
- catName = (String) category.get("name");
- catDef.setName(catName);
- icons = (List<String>) category.get("icons");
- catDef.setIcons(icons);
- String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName);
- catDef.setNormalizedName(normalizedName);
- oldName = (String) category.get("oldName");
- catDef.setOldName(oldName);
- categroiesDef.add(catDef);
- }
-
- return categroiesDef;
- }
-
- private List<MigrationCategory> createResourceCategories(Map<String, Object> categoryPerType) {
- List<MigrationCategory> categroiesDef = new ArrayList<>();
- for (Map.Entry<String, Object> entry : categoryPerType.entrySet()) {
- Map<String, Object> category = (Map<String, Object>) entry.getValue();
- MigrationCategory catDef = new MigrationCategory();
- String catName = (String) category.get("name");
- catDef.setName(catName);
- String normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(catName);
- catDef.setNormalizedName(normalizedName);
- String oldName = (String) category.get("oldName");
- catDef.setOldName(oldName);
-
- Map<String, Object> subcategories = (Map<String, Object>) category.get("subcategories");
- List<MigrationSubCategory> subcateDef = new ArrayList<>();
- for (Entry<String, Object> subcategory : subcategories.entrySet()) {
- Map<String, Object> subcategoryInfo = (Map<String, Object>) subcategory.getValue();
- MigrationSubCategory subDef = new MigrationSubCategory();
- String subcategoryName = (String) subcategoryInfo.get("name");
- subDef.setName(subcategoryName);
- List<String> subcategoryIcons = (List<String>) subcategoryInfo.get("icons");
- subDef.setIcons(subcategoryIcons);
- normalizedName = ValidationUtils.normalizeCategoryName4Uniqueness(subcategoryName);
- subDef.setNormalizedName(normalizedName);
- oldName = (String) subcategoryInfo.get("oldName");
- subDef.setOldName(oldName);
-
- subcateDef.add(subDef);
- }
-
- catDef.setSubcategories(subcateDef);
- categroiesDef.add(catDef);
- }
- return categroiesDef;
- }
-
- private boolean updateCalculatedEdges() {
- log.debug("update calculated edges STARTED");
-
- Either<List<ComponentInstanceData>, TitanOperationStatus> allInstances = titanGenericDao.getByCriteria(NodeTypeEnum.ResourceInstance, null, ComponentInstanceData.class);
- if (allInstances.isRight() && !allInstances.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("updateCalculatedEdges failed fetch all resource instances ,error " + allInstances.right().value());
- return false;
- }
- if (allInstances.isRight() && allInstances.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("updateCalculatedEdges - no VFs");
- return true;
- }
- List<ComponentInstanceData> listOfInstances = allInstances.left().value();
- for (ComponentInstanceData instance : listOfInstances) {
- // check if already have calculated edges
- log.debug("start handle instance {}", instance.getUniqueId());
- boolean needProcess = true;
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> vfci = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), instance.getUniqueId(),
- GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class);
- if (vfci.isRight()) {
- if (!vfci.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("createCalculatedCapabilitiesForInstance failed to fetch instance for resource " + instance.getComponentInstDataDefinition().getComponentUid() + " error " + vfci.right().value());
- return false;
- }
- } else {
- if (vfci.left().value().size() > 0) {
- needProcess = false;
- }
- }
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> vfciReq = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), instance.getUniqueId(),
- GraphEdgeLabels.CALCULATED_REQUIREMENT, NodeTypeEnum.Requirement, RequirementData.class);
- if (vfciReq.isRight()) {
- if (!vfciReq.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("createCalculatedCapabilitiesForInstance failed to fetch instance for resource " + instance.getComponentInstDataDefinition().getComponentUid() + " error " + vfciReq.right().value());
- return false;
- }
- } else {
- if (vfciReq.left().value().size() > 0) {
- needProcess = false;
- }
- }
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> vfciReqFF = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), instance.getUniqueId(),
- GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED, NodeTypeEnum.Requirement, RequirementData.class);
- if (vfciReqFF.isRight()) {
-
- if (!vfciReqFF.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("createCalculatedCapabilitiesForInstance failed to fetch instance for resource " + instance.getComponentInstDataDefinition().getComponentUid() + " error " + vfciReqFF.right().value());
- return false;
- }
- } else {
- if (vfciReqFF.left().value().size() > 0) {
- needProcess = false;
- }
- }
-
- if (needProcess == false) {
- log.debug("updateCalculatedEdges : for instance {} calculated capabilty/requirement already created", instance.getUniqueId());
- continue;
- }
- String originId = instance.getComponentInstDataDefinition().getComponentUid();
- Either<Resource, StorageOperationStatus> resourceE = resourceOperation.getResource(originId, true);
- if (resourceE.isRight()) {
- log.debug("updateCalculatedEdges failed to fetch origin resource with id {} error {}", originId, resourceE.right().value());
- return false;
- }
- Resource resource = resourceE.left().value();
- Map<String, List<RequirementDefinition>> requirements = resource.getRequirements();
- if (createCalculatedRequirementsForInstance(instance, requirements) != true) {
- return false;
- }
- Map<String, List<CapabilityDefinition>> capabilities = resource.getCapabilities();
- if (createCalculatedCapabilitiesForInstance(instance, capabilities) != true) {
- return false;
- }
- log.debug("finish handle instance {}", instance.getUniqueId());
- }
- log.debug("update calculated edges ENDED");
- return true;
- }
-
- private boolean createCalculatedCapabilitiesForInstance(ComponentInstanceData instance, Map<String, List<CapabilityDefinition>> capabilities) {
- for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
- for (CapabilityDefinition capability : entry.getValue()) {
- Either<CapabilityData, TitanOperationStatus> capNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capability.getUniqueId(), CapabilityData.class);
- if (capNode.isRight()) {
- log.debug("createCalculatedCapabilitiesForInstance failed to fetch capability node with id " + capability.getUniqueId() + " error " + capNode.right().value());
- return false;
- }
- Map<String, Object> props = new HashMap<>();
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capability.getName());
- if (fillEdgeProperties(instance, props) != true) {
- return false;
- }
-
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(instance, capNode.left().value(), GraphEdgeLabels.CALCULATED_CAPABILITY, props);
- if (createRelation.isRight()) {
- TitanOperationStatus titanOperationStatus = createRelation.right().value();
- log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", instance.getUniqueId(), capNode.left().value().getUniqueId(), titanOperationStatus);
- return false;
- }
- log.debug("CALCULATED_CAPABILITY was created from {} to {} with props : {}", capNode.left().value().getUniqueId(), instance.getUniqueId(), props);
- }
- }
- return true;
- }
-
- private boolean fillEdgeProperties(ComponentInstanceData instance, Map<String, Object> props) {
- if (instance.getComponentInstDataDefinition().getOriginType().equals(OriginTypeEnum.VF)) {
- Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> vfci = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource),
- instance.getComponentInstDataDefinition().getComponentUid(), GraphEdgeLabels.RESOURCE_INST, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
- if (vfci.isRight()) {
- log.debug("createCalculatedCapabilitiesForInstance failed to fetch instance for resource " + instance.getComponentInstDataDefinition().getComponentUid() + " error " + vfci.right().value());
- return false;
- }
- ImmutablePair<ComponentInstanceData, GraphEdge> immutablePair = vfci.left().value().get(0);
- String vfciId = immutablePair.getLeft().getUniqueId();
- props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), vfciId);
- props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(), immutablePair.getLeft().getComponentInstDataDefinition().getComponentUid());
-
- } else {
- props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), instance.getUniqueId());
- props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(), instance.getComponentInstDataDefinition().getComponentUid());
- }
- return true;
- }
-
- private boolean createCalculatedRequirementsForInstance(ComponentInstanceData instance, Map<String, List<RequirementDefinition>> requirements) {
- for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
- for (RequirementDefinition requirement : entry.getValue()) {
- Either<RequirementData, TitanOperationStatus> reqNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirement.getUniqueId(), RequirementData.class);
- if (reqNode.isRight()) {
- log.debug("updateCalculatedEdges failed to fetch requirement node with id " + requirement.getUniqueId() + " error " + reqNode.right().value());
- return false;
- }
- Map<String, Object> props = new HashMap<>();
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), requirement.getName());
-
- if (fillEdgeProperties(instance, props) != true) {
- return false;
- }
-
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(instance, reqNode.left().value(), GraphEdgeLabels.CALCULATED_REQUIREMENT, props);
- if (createRelation.isRight()) {
- TitanOperationStatus titanOperationStatus = createRelation.right().value();
- log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", instance.getUniqueId(), reqNode.left().value().getUniqueId(), titanOperationStatus);
- return false;
- }
- log.debug("CALCULATED_REQUIREMENT was created from {} to {} with props : {}", reqNode.left().value().getUniqueId(), instance.getUniqueId(), props);
- }
- }
- return true;
- }
-
- private boolean updateRelations() {
- log.debug("update relations and edges STARTED");
- Either<List<RelationshipInstData>, TitanOperationStatus> allRelations = titanGenericDao.getByCriteria(NodeTypeEnum.RelationshipInst, null, RelationshipInstData.class);
- if (allRelations.isRight()) {
- if (allRelations.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("updateRelations : No relations to update. updateRelations ENDED");
- return true;
- }
- log.debug("updateRelations : failed to fetch all relation nodes , error ", allRelations.right().value());
- return false;
- }
- for (RelationshipInstData rel : allRelations.left().value()) {
- // rel.set
- if (rel.getCapabilityOwnerId() != null && rel.getRequirementOwnerId() != null) {
- log.debug("updateRelations : for relation {} all fields alredy fixed -> {}", rel.getUniqueId(), rel);
- continue;
- }
- // update capability parameters
- if (updateCapabiltyFieldsInRelation(rel) != true) {
- return false;
- }
-
- // update requirement parameters and set calculated edge to full
- // filled
- if (updateRequirementFieldsInRelation(rel) != true) {
- return false;
- }
-
- Either<RelationshipInstData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(rel, RelationshipInstData.class);
- if (updateNode.isRight()) {
- log.debug("updateRelations : failed to update relation node with id {} , error {}", rel.getUniqueId(), updateNode.right().value());
- return false;
- }
- log.debug("Relations was updated with values {}", rel);
- }
- log.debug("update relations and edges ENDED");
- return true;
- }
-
- private boolean updateRequirementFieldsInRelation(RelationshipInstData rel) {
- Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> reqInst = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipInst), rel.getUniqueId(), GraphEdgeLabels.RELATIONSHIP_INST,
- NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
- if (reqInst.isRight()) {
- log.debug("updateRelations : failed to fetch capability component instance for relation {}, error {}", rel.getUniqueId(), reqInst.right().value());
- return false;
- }
- ComponentInstanceData requirementInstanceData = reqInst.left().value().getLeft();
- ComponentInstanceDataDefinition reqRI = requirementInstanceData.getComponentInstDataDefinition();
- if (reqRI.getOriginType().equals(OriginTypeEnum.VF)) {
- Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> vfcInstInOrigVf = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), reqRI.getComponentUid(),
- GraphEdgeLabels.RESOURCE_INST, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class, null);
- if (vfcInstInOrigVf.isRight()) {
- log.debug("updateRelations : failed to fetch VFC instance in origin VF with id " + reqRI.getComponentUid() + ", error ", vfcInstInOrigVf.right().value());
- return false;
- }
- rel.setRequirementOwnerId(vfcInstInOrigVf.left().value().getLeft().getUniqueId());
- } else {
- rel.setRequirementOwnerId(reqRI.getUniqueId());
- }
- // get vertex
- Either<TitanVertex, TitanOperationStatus> vertexReqRI = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), requirementInstanceData.getUniqueId());
- if (vertexReqRI.isRight()) {
- log.debug("updateRelations : failed to fetch veterx for instance {}, error {}", requirementInstanceData.getUniqueId(), vertexReqRI.right().value());
- return false;
- }
- String[] splitIds = rel.getUniqueId().split("\\.");
- String reqName = splitIds[splitIds.length - 1];
- Map<String, Object> props = new HashMap<>();
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), reqName);
- Either<List<Edge>, TitanOperationStatus> edgesForNode = titanGenericDao.getOutgoingEdgesByCriteria(vertexReqRI.left().value(), GraphEdgeLabels.CALCULATED_REQUIREMENT, props);
- if (edgesForNode.isRight()) {
- log.debug("updateRelations : failed to fetch edges for instance {} error {}", requirementInstanceData.getUniqueId(), edgesForNode.right().value());
- return false;
- }
- Edge edge = edgesForNode.left().value().get(0);
- String reqId = (String) titanGenericDao.getProperty((TitanVertex) edge.inVertex(), GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- rel.setRequirementId(reqId);
-
- // change edge label
- TitanEdge newEdge = (TitanEdge) vertexReqRI.left().value().addEdge(GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED.getProperty(), edge.inVertex());
- titanGenericDao.setProperties(newEdge, titanGenericDao.getProperties(edge));
- edge.remove();
-
- log.debug("Edge was changed to CALCULATED_REQUIREMENT_FULLFILLED for relation between {} and {}", reqId, requirementInstanceData.getUniqueId());
-
- return true;
- }
-
- public boolean updateCapabiltyFieldsInRelation(RelationshipInstData rel) {
- // update capability parameters
- Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> capInst = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipInst), rel.getUniqueId(),
- GraphEdgeLabels.CAPABILITY_NODE, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class, null);
- if (capInst.isRight()) {
- log.debug("updateRelations : failed to fetch capabilty component instance for relation {}, error {}", rel.getUniqueId(), capInst.right().value());
- return false;
- }
- ComponentInstanceData capabiltyInstanceData = capInst.left().value().getLeft();
- ComponentInstanceDataDefinition capRI = capabiltyInstanceData.getComponentInstDataDefinition();
- if (capRI.getOriginType().equals(OriginTypeEnum.VF)) {
- Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> vfcInstInOrigVf = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), capRI.getComponentUid(),
- GraphEdgeLabels.RESOURCE_INST, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class, null);
- if (vfcInstInOrigVf.isRight()) {
- log.debug("updateRelations : failed to fetch VFC instance in origin VF with id " + capRI.getComponentUid() + ", error ", vfcInstInOrigVf.right().value());
- return false;
- }
- rel.setCapabilityOwnerId(vfcInstInOrigVf.left().value().getLeft().getUniqueId());
- } else {
- rel.setCapabilityOwnerId(capRI.getUniqueId());
- }
-
- // get vertex
- Either<TitanVertex, TitanOperationStatus> vertexCapRI = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), capabiltyInstanceData.getUniqueId());
- if (vertexCapRI.isRight()) {
- log.debug("updateRelations : failed to fetch veterx for instance {} , error {}", capabiltyInstanceData.getUniqueId(), vertexCapRI.right().value());
- return false;
- }
- // String[] splitIds = rel.getUniqueId().split("\\.");
- String capName = (String) capInst.left().value().getRight().getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty());// splitIds[splitIds.length
- // - 1];
- Map<String, Object> props = new HashMap<>();
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capName);
- Either<List<Edge>, TitanOperationStatus> edgesForNode = titanGenericDao.getOutgoingEdgesByCriteria(vertexCapRI.left().value(), GraphEdgeLabels.CALCULATED_CAPABILITY, props);
- if (edgesForNode.isRight()) {
- log.debug("updateRelations : failed to fetch edges for instance {} , error {}", capabiltyInstanceData.getUniqueId(), edgesForNode.right().value());
- return false;
- }
- Edge edge = edgesForNode.left().value().get(0);
- String capId = (String) titanGenericDao.getProperty((TitanVertex) edge.inVertex(), GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- rel.setCapabiltyId(capId);
-
- return true;
- }
-
- private Either<List<String>, StorageOperationStatus> handleVfGroup(ResourceMetadataData metadata) {
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
- props.put(GraphPropertiesDictionary.NAME.getProperty(), metadata.getMetadataDataDefinition().getName());
-
- List<String> finished = new ArrayList<>();
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> allVFByName = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
- if (allVFByName.isRight()) {
- log.debug("fixDerivedFv failed fetch all VF resources,error {}", allVFByName.right().value());
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- Set<String> nonDuplicatedId = new HashSet<>();
- String uuid10 = null;
- for (ResourceMetadataData mdata : allVFByName.left().value()) {
- String version = mdata.getMetadataDataDefinition().getVersion();
- if (version.equals("1.0")) {
- uuid10 = mdata.getMetadataDataDefinition().getUUID();
- // break;
- }
- nonDuplicatedId.add((String) mdata.getUniqueId());
- }
- if (uuid10 == null) {
- uuid10 = allVFByName.left().value().get(0).getMetadataDataDefinition().getUUID();
- }
- props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
- props.put(GraphPropertiesDictionary.UUID.getProperty(), uuid10);
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> allVFByUUID = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
- if (allVFByUUID.isRight()) {
- log.debug("fixDerivedFv failed fetch all VF resources by UUID {} ,error {}", uuid10, allVFByUUID.right().value());
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- for (ResourceMetadataData mdata : allVFByUUID.left().value()) {
- nonDuplicatedId.add((String) mdata.getUniqueId());
- }
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- if (graph.isRight()) {
- log.debug("fixDerivedFv failed - No titan graph ,error {}", graph.right().value());
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- // Map<String, String> derivedMapping = new HashMap<>();
- for (String resourceId : nonDuplicatedId) {
- // StorageOperationStatus handleSingleVfResult =
- // handleSingleVf(finished, derivedMapping, resourceId);
- StorageOperationStatus handleSingleVfResult = handleSingleVf(finished, resourceId);
- if (!handleSingleVfResult.equals(StorageOperationStatus.OK)) {
- log.debug("fixDerivedFv failed - handleSingleVfResult failed for resource {} ,error {}", resourceId, handleSingleVfResult);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- }
- return Either.left(finished);
- }
-
- // private StorageOperationStatus handleSingleVf(List<String> finished,
- // Map<String, String> derivedMapping, String resourceId) {
- private StorageOperationStatus handleSingleVf(List<String> finished, String resourceId) {
- Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId);
- if (vertexByProperty.isRight()) {
- log.debug("fixDerivedFv failed to fetch resource by id {} ,error {}", resourceId, vertexByProperty.right().value());
- return StorageOperationStatus.GENERAL_ERROR;
- }
- Vertex vertexR = vertexByProperty.left().value();
- Iterator<Vertex> vertexDIter = vertexR.vertices(Direction.OUT, GraphEdgeLabels.DERIVED_FROM.getProperty());
- if (vertexDIter != null && vertexDIter.hasNext()) {
- // move edges
- // must be only one
- TitanVertex vertexD = (TitanVertex) vertexDIter.next();
- String idDerived = (String) titanGenericDao.getProperty(vertexD, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
-
- // TODO clone resource
-
- // TODO add instance of new resource to VF
-
- // add to vf instance of vfc
- finished.add(resourceId);
- } else {
- log.debug("No derived edges for resource id {}", resourceId);
- }
- return StorageOperationStatus.OK;
- }
-
- private boolean updateComponentInstanceType() {
- log.debug("update component instances type STARTED");
- Either<List<ComponentInstanceData>, TitanOperationStatus> allInstances = titanGenericDao.getByCriteria(NodeTypeEnum.ResourceInstance, null, ComponentInstanceData.class);
- if (allInstances.isRight()) {
- if (allInstances.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("updateComponentInstanceType: no instances ti update ");
- return true;
- }
- log.debug("updateComponentInstanceType failed fetch all resource instances ,error " + allInstances.right().value());
- return false;
- }
-
- List<ComponentInstanceData> listOfInstances = allInstances.left().value();
- for (ComponentInstanceData instance : listOfInstances) {
- String originId = instance.getComponentInstDataDefinition().getComponentUid();
- Either<ComponentMetadataData, TitanOperationStatus> nodeResource = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), originId, ComponentMetadataData.class);
- if (nodeResource.isRight()) {
- log.debug("updateComponentInstanceType failed to fetch origin resource with id {} error {}", originId, nodeResource.right().value());
- return false;
- }
- ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) nodeResource.left().value().getMetadataDataDefinition()).getResourceType();
- if (resourceType == null) {
- log.debug("updateComponentInstanceType failed, no resource type for origin resource with id " + originId);
- return false;
- }
- OriginTypeEnum originType;
- switch (resourceType) {
- case VF:
- originType = OriginTypeEnum.VF;
- break;
- case VFC:
- originType = OriginTypeEnum.VFC;
- break;
- case VL:
- originType = OriginTypeEnum.VL;
- break;
- case CP:
- originType = OriginTypeEnum.CP;
- break;
- case CVFC:
- originType = OriginTypeEnum.CVFC;
- break;
- default:
- log.debug("updateComponentInstanceType failed, no supported resource type {} for origin resource with id {}", resourceType, originId);
- return false;
- }
- instance.getComponentInstDataDefinition().setOriginType(originType);
-
- Either<ComponentInstanceData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(instance, ComponentInstanceData.class);
- if (updateNode.isRight()) {
- log.debug("updateComponentInstanceType failed, failed to update component instance node with id " + instance.getUniqueId() + " error " + updateNode.right().value());
- return false;
- }
- log.debug("For instance with id {} the origin type was detected as {}", instance.getUniqueId(), originType);
- }
- log.debug("update component instances type ENDED");
- return true;
- }
-
- private boolean addResourceCounterToResources() {
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> allResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, null, ResourceMetadataData.class);
- if (allResources.isRight()) {
- if (allResources.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("addResourceCounterToResources - no resources");
- return true;
- }
- log.debug("addResourceCounterToResources failed fetch all resources,error {}", allResources.right().value());
- return false;
- }
- for (ResourceMetadataData resource : allResources.left().value()) {
- Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId());
- if (vertexByProperty.isRight()) {
- log.error("failed to add instanceCounter to VF {} . error is: {}", resource.getUniqueId(), vertexByProperty.right().value().name());
- return false;
- }
- Vertex vfVertex = vertexByProperty.left().value();
- if (!vfVertex.property(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty()).isPresent()) {
- vfVertex.property(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty(), 0);
- }
- }
- return true;
- }
-
- private boolean fixDerivedVf() {
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
- Either<List<ResourceMetadataData>, TitanOperationStatus> allVF = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
- if (allVF.isRight()) {
- if (allVF.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("fixDerivedVf - no VFs");
- return true;
- }
- log.debug("fixDerivedFv failed fetch all VF resources,error {}", allVF.right().value());
- return false;
- }
-
- Map<String, String> vfUuidToVfcUuid = new HashMap<String, String>();
- for (ResourceMetadataData metadata : allVF.left().value()) {
- Either<Resource, StorageOperationStatus> eitherResource = resourceOperation.getResource(metadata.getMetadataDataDefinition().getUniqueId(), true);
- if (eitherResource.isRight()) {
- log.error("failed to migrate VF {} from version 1602 to version 1604. error is: {}", metadata.getMetadataDataDefinition().getUniqueId(), eitherResource.right().value().name());
- return false;
- }
- Resource vfResource = eitherResource.left().value();
- if (vfResource.getDerivedFrom() == null || vfResource.getDerivedFrom().isEmpty()) {
- continue;
- }
- Boolean isVfDeleted = vfResource.getIsDeleted();
- String vfUUID = vfResource.getUUID();
- String vfcUUID = vfUuidToVfcUuid.getOrDefault(vfUUID, null);
- if (vfcUUID == null) {
- vfcUUID = UUID.randomUUID().toString();
- vfUuidToVfcUuid.put(vfUUID, vfcUUID);
- }
-
- // handle lifecycle
- String vfUniqueId = vfResource.getUniqueId();
- LifecycleStateEnum vfcTargetState = vfResource.getLifecycleState();
- if (vfcTargetState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION) || vfcTargetState.equals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS)) {
- User user = new User();
- user.setUserId(vfResource.getLastUpdaterUserId());
- Either<? extends Component, StorageOperationStatus> checkinComponent = lifecycleOperaion.checkinComponent(NodeTypeEnum.Resource, vfResource, user, user, true);
- if (checkinComponent.isRight()) {
- log.error("failed to checkin VF {}. error={}", vfUniqueId, checkinComponent.right().value().name());
- return false;
- }
- } else if (vfcTargetState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
- vfcTargetState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN;
- }
-
- // delete VF Properties
- List<PropertyDefinition> properties = vfResource.getProperties();
- if (properties != null && !properties.isEmpty()) {
- Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllProperties = propertyOperation.deleteAllPropertiesAssociatedToNode(NodeTypeEnum.Resource, vfUniqueId);
- if (deleteAllProperties.isRight() && !deleteAllProperties.right().value().equals(StorageOperationStatus.NOT_FOUND) && !deleteAllProperties.right().value().equals(StorageOperationStatus.OK)) {
- log.error("failed to delete properties of VF {} . error is: {}", metadata.getMetadataDataDefinition().getUniqueId(), deleteAllProperties.right().value().name());
- return false;
- }
- }
- // delete VF Additional Info
- List<AdditionalInformationDefinition> additionalInformation = vfResource.getAdditionalInformation();
- if (additionalInformation != null && !additionalInformation.isEmpty()) {
- Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters = additionalInformationOperation.deleteAllAdditionalInformationParameters(NodeTypeEnum.Resource, vfUniqueId, true);
- if (deleteAllAdditionalInformationParameters.isRight() && !deleteAllAdditionalInformationParameters.right().value().equals(StorageOperationStatus.OK)
- && !deleteAllAdditionalInformationParameters.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- log.error("failed to delete properties of VF {} . error is: {}", metadata.getMetadataDataDefinition().getUniqueId(), deleteAllAdditionalInformationParameters.right().value().name());
- return false;
- }
- }
- // delete VF derivedFrom
- GraphRelation derivedFromRelation = new GraphRelation(GraphEdgeLabels.DERIVED_FROM.getProperty());
- derivedFromRelation.setFrom(new RelationEndPoint(NodeTypeEnum.Resource, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), vfUniqueId));
- Either<GraphRelation, TitanOperationStatus> deleteDerivedFromRelation = titanGenericDao.deleteOutgoingRelation(derivedFromRelation);
- if (deleteDerivedFromRelation.isRight()) {
- log.error("failed to delete derivedFrom relation of VF {} . error is: {}", metadata.getMetadataDataDefinition().getUniqueId(), deleteDerivedFromRelation.right().value().name());
- return false;
- }
-
- // create VFC
- Either<Resource, StorageOperationStatus> createVFC = createVFC(metadata, vfResource, vfcUUID, vfcTargetState);
- if (createVFC.isRight()) {
- log.error("failed to split VF {} to VFC. error is: {}", metadata.getMetadataDataDefinition().getUniqueId(), createVFC.right().value().name());
- return false;
- }
- Resource vfcResource = createVFC.left().value();
- if (!createVfcInstanceOnVf(vfcResource, vfUniqueId)) {
- return false;
- }
- // update VFC to deleted if required
- if (isVfDeleted != null && isVfDeleted) {
- Either<Component, StorageOperationStatus> markResourceToDelete = resourceOperation.markComponentToDelete(vfcResource, true);
- if (markResourceToDelete.isRight()) {
- log.error("failed to mark isDeleted on VFC {} . error is: {}", vfcResource.getUniqueId(), markResourceToDelete.right().value().name());
- return false;
- }
- }
-
- }
- return true;
- }
-
- private Either<Resource, StorageOperationStatus> createVFC(ResourceMetadataData metadata, Resource vfcResource, String uuid, LifecycleStateEnum vfcTargetState) {
-
- Boolean highestVersion = vfcResource.isHighestVersion();
- // Resource vfcResource = new Resource((ResourceMetadataDefinition)
- // vfResource.getComponentMetadataDefinition());
- // String componentName = vfcResource.getName()+"VFC";
- // vfcResource.setName(componentName);
- // vfcResource.setNormalizedName(ValidationUtils.normaliseComponentName(componentName));
- // vfcResource.setSystemName(ValidationUtils.convertToSystemName(componentName));
- vfcResource.setUniqueId(null);
- vfcResource.setUUID(uuid);
- vfcResource.setAllVersions(null);
- vfcResource.setArtifacts(null);
- vfcResource.setDeploymentArtifacts(null);
- vfcResource.setComponentInstances(null);
- vfcResource.setComponentInstancesProperties(null);
- vfcResource.setComponentInstancesRelations(null);
- vfcResource.setResourceType(ResourceTypeEnum.VFC);
- vfcResource.setIsDeleted(false);
-
- vfcResource.setLifecycleState(vfcTargetState);
- // vfcResource.setDerivedFrom(vfResource.getDerivedFrom());
- // vfcResource.setProperties(vfResource.getProperties());
- // vfcResource.setAdditionalInformation(vfResource.getAdditionalInformation());
- // vfcResource.setCategories(vfResource.getCategories());
- // vfcResource.setTags(vfResource.getTags());
-
- Either<Resource, StorageOperationStatus> createResource = resourceOperation.createResource(vfcResource, true);
- if (createResource.isRight()) {
- return createResource;
- }
- Resource afterCreateResource = createResource.left().value();
- Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), afterCreateResource.getUniqueId());
- if (vertexByProperty.isRight()) {
- return createResource;
- }
- Vertex newVfcVertex = vertexByProperty.left().value();
- newVfcVertex.property(GraphPropertiesDictionary.UUID.getProperty(), uuid);
- if (!highestVersion) {
- newVfcVertex.property(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), false);
- }
- return createResource;
- }
-
- private boolean createVfcInstanceOnVf(Resource vfcResource, String vfUniqueId) {
- // create VFC instance on VF
- ComponentInstance componentInstance = new ComponentInstance();
- componentInstance.setComponentUid(vfcResource.getUniqueId());
- componentInstance.setPosX("550");
- componentInstance.setPosY("300");
- componentInstance.setName(vfcResource.getName());
- componentInstance.setIcon(vfcResource.getIcon());
- componentInstance.setToscaComponentName(vfcResource.getToscaResourceName());
- Either<String, Boolean> handleNameLogic = handleNameLogic(componentInstance, vfUniqueId, vfcResource.getName());
- if (handleNameLogic.isRight()) {
- log.error("failed to create logical name for vfc instance");
- return false;
- }
- Either<ComponentInstance, StorageOperationStatus> createComponentInstance = componentInstanceOperaion.createComponentInstance(vfUniqueId, NodeTypeEnum.Resource, handleNameLogic.left().value(), componentInstance, NodeTypeEnum.Resource, true);
-
- if (createComponentInstance.isRight()) {
- log.error("failed to create vfc instance on vf {}. error: {}", vfUniqueId, createComponentInstance.right().value().name());
- return false;
- }
- return true;
- }
-
- private Either<String, Boolean> handleNameLogic(ComponentInstance componentInstance, String containerComponentId, String resourceName) {
-
- Either<Integer, StorageOperationStatus> componentInNumberStatus = resourceOperation.increaseAndGetComponentInstanceCounter(containerComponentId, true);
-
- if (componentInNumberStatus.isRight()) {
- log.debug("Failed to get component instance number for container component {} ", containerComponentId);
- return Either.right(false);
- }
- String resourceInNumber = componentInNumberStatus.left().value().toString();
- componentInstance.setComponentName(resourceName);
- componentInstance.setName(resourceName);
- String logicalName = componentInstanceOperaion.createComponentInstLogicalName(resourceInNumber, resourceName);
-
- Boolean eitherValidation = validateComponentInstanceName(logicalName, componentInstance, true);
- if (!eitherValidation) {
- return Either.right(false);
- }
-
- return Either.left(resourceInNumber);
- }
-
- private Boolean validateComponentInstanceName(String resourceInstanceName, ComponentInstance resourceInstance, boolean isCreate) {
-
- if (!ValidationUtils.validateStringNotEmpty(resourceInstanceName)) {
- return false;
- }
- resourceInstance.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceName));
- if (!isCreate) {
- if (!ValidationUtils.validateResourceInstanceNameLength(resourceInstanceName)) {
- return false;
- }
- if (!ValidationUtils.validateResourceInstanceName(resourceInstanceName)) {
- return false;
- }
- }
-
- return true;
-
- }
-
- public boolean migrate1604to1607(String appConfigDir) {
- log.debug("Started the migration procedure from version 1604 to version 1607 ...");
- log.debug("Getting all resources with resources");
- boolean result = false;
- Either<Boolean, StorageOperationStatus> resourceEither = null;
- try {
- Either<List<ResourceMetadataData>, TitanOperationStatus> allResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, null, ResourceMetadataData.class);
- if (allResources.isRight()) {
- log.error("Couldn't get resources from DB, error: {}", allResources.right().value());
- result = false;
- return result;
- }
- List<ResourceMetadataData> resourcesList = allResources.left().value();
- if (resourcesList == null) {
- log.error("Couldn't get resources from DB, no resources found");
- result = false;
- return result;
- }
- log.debug("Found {} resources", resourcesList.size());
- for (ResourceMetadataData resource : resourcesList) {
- String resourceName = resource.getMetadataDataDefinition().getName();
- log.debug("Checking resource {}", resourceName);
- if (isNormative(resourceName)) {
- resourceEither = changeNormativeTypeName(resource);
- if (resourceEither.isRight()) {
- log.error("DB error during name changing");
- result = false;
- return result;
- }
- }
- if (((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).getResourceType().name().equals("VF")) {
- resourceEither = setVfToscaResourceName(resource);
- if (resourceEither.isRight()) {
- log.error("DB error during tosca resource name setting");
- result = false;
- return result;
- }
- }
- }
- result = addInvariantUUIDs(appConfigDir);
- } finally {
- if (!result) {
- titanGenericDao.rollback();
- log.debug("**********************************************");
- log.debug("The migration procedure from version 1604 to version 1607 FAILED!!");
- log.debug("**********************************************");
- } else {
- titanGenericDao.commit();
- log.debug("**********************************************");
- log.debug("The migration procedure from version 1604 to version 1607 ended successfully!");
- log.debug("**********************************************");
- }
- }
-
- return result;
- }
-
- private boolean addInvariantUUIDs(String appConfigDir) {
- log.debug("Started adding of InvariantUUID ...");
- log.debug("Getting all resources with highest version");
-
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
-
- List<ComponentMetadataData> fullComponentList = new ArrayList<ComponentMetadataData>();
-
- // getting resources
- Either<List<ResourceMetadataData>, TitanOperationStatus> allHighestVersionResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
- if (allHighestVersionResources.isRight()) {
- log.error("Couldn't get resources with highest version from DB, error: {}", allHighestVersionResources.right().value());
- return false;
- }
- List<ResourceMetadataData> allHighestVersionResourcesAL = allHighestVersionResources.left().value();
- if (allHighestVersionResourcesAL == null) {
- log.error("Couldn't get resources with highest version from DB, no resources found");
- return false;
- }
- log.debug("Found {} resources", allHighestVersionResourcesAL.size());
- fullComponentList.addAll(allHighestVersionResourcesAL);
-
- // getting services
- Either<List<ServiceMetadataData>, TitanOperationStatus> allHighestVersionServices = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class);
- if (allHighestVersionServices.isRight()) {
- log.error("Couldn't get services with highest version from DB, error: {}", allHighestVersionServices.right().value());
- return false;
- }
- List<ServiceMetadataData> allHighestVersionServicesAL = allHighestVersionServices.left().value();
- if (allHighestVersionServicesAL == null) {
- log.error("Couldn't get services with highest version from DB, no services found");
- return false;
- }
- log.debug("Found {} services", allHighestVersionServicesAL.size());
- fullComponentList.addAll(allHighestVersionServicesAL);
-
- List<ComponentMetadataData> reducedComponentsAL = reduceHighestVersionResourcesList(fullComponentList);
-
- // getting products
- Either<List<ProductMetadataData>, TitanOperationStatus> allHighestVersionProducts = titanGenericDao.getByCriteria(NodeTypeEnum.Product, props, ProductMetadataData.class);
- if (allHighestVersionProducts.isRight()) {
- log.error("Couldn't get products with highest version from DB, error: {}", allHighestVersionProducts.right().value());
- return false;
- }
- List<ProductMetadataData> allHighestVersionProductsAL = allHighestVersionProducts.left().value();
- if (allHighestVersionProductsAL == null) {
- log.error("Couldn't get products with highest version from DB, no products found");
- return false;
- }
- log.debug("Found {} products", allHighestVersionProductsAL.size());
-
- List<ComponentMetadataData> fullProductList = new ArrayList<ComponentMetadataData>();
- fullProductList.addAll(allHighestVersionProductsAL);
- List<ComponentMetadataData> reducedProductAL = reduceHighestVersionResourcesList(fullProductList);
-
- for (ComponentMetadataData product : reducedProductAL) {
- if (!setProductInvariantUUIDIfExists((ProductMetadataData) product)) {
- return false;
- }
- }
- reducedComponentsAL.addAll(reducedProductAL);
-
- log.debug("Reduced list of Highest Version Components contains {} components", reducedComponentsAL.size());
- for (ComponentMetadataData componentMetaData : reducedComponentsAL) {
-
- String invariantUUID = componentMetaData.getMetadataDataDefinition().getInvariantUUID();
- log.debug("old invariantUUID {}", invariantUUID);
- if (invariantUUID == null || invariantUUID.isEmpty()) {
- invariantUUID = UniqueIdBuilder.buildInvariantUUID();
- componentMetaData.getMetadataDataDefinition().setInvariantUUID(invariantUUID);
- }
- log.debug("new invariantUUID {}", componentMetaData.getMetadataDataDefinition().getInvariantUUID());
- Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentMetaData, ComponentMetadataData.class);
- if (updateNode.isRight()) {
- log.error("DB error during while updating component {}, error: {}", componentMetaData.getMetadataDataDefinition().getName(), updateNode.right().value());
- return false;
- }
- log.debug("updated invariantUUID {}", updateNode.left().value().getMetadataDataDefinition().getInvariantUUID());
- if (!isOnlyVersion(componentMetaData)) {
- ComponentOperation componentOperation = null;
- switch (NodeTypeEnum.getByName(componentMetaData.getLabel())) {
- case Resource:
- componentOperation = resourceOperation;
- break;
- case Service:
- componentOperation = serviceOperation;
- break;
- case Product:
- componentOperation = productOperation;
- break;
- default:
- break;
- }
- Either<Component, StorageOperationStatus> getComponentResult = componentOperation.getComponent((String) componentMetaData.getUniqueId(), true);
- if (getComponentResult.isRight()) {
- log.error("DB error during while getting component with uniqueID {}, error: {}", componentMetaData.getUniqueId(), getComponentResult.right().value());
- return false;
- }
- Component component = getComponentResult.left().value();
- if (component == null) {
- log.error("The component received from DB is empty");
- return false;
- }
-
- Map<String, String> allVersions = component.getAllVersions();
- log.debug("found {} versions for component {}", allVersions.size(), component.getName());
- Either<Boolean, StorageOperationStatus> resEither = updateAllVersions(allVersions, invariantUUID);
- if (resEither.isRight()) {
- log.error("DB error during invariantUUID adding");
- return false;
- }
- }
- }
- return true;
- }
-
- private boolean isOnlyVersion(ComponentMetadataData componentMetaData) {
- String version = componentMetaData.getMetadataDataDefinition().getVersion();
- if (version.equals("0.1"))
- return true;
- return false;
- }
-
- private boolean setProductInvariantUUIDIfExists(ProductMetadataData product) {
- Either<TitanVertex, TitanOperationStatus> getVertexRes = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), product.getUniqueId());
- if (getVertexRes.isRight()) {
- log.error("DB error during retrieving product vertex {}", product.getMetadataDataDefinition().getName());
- return false;
- }
- Vertex productVertex = getVertexRes.left().value();
- String invariantUUID = productVertex.value(GraphPropertiesDictionary.CONSTANT_UUID.getProperty());
- if (invariantUUID != null && !invariantUUID.isEmpty()) {
- product.getMetadataDataDefinition().setInvariantUUID(invariantUUID);
- }
- return true;
- }
-
- private Either<Boolean, StorageOperationStatus> updateAllVersions(Map<String, String> allVersions, String invariantUUID) {
-
- if (allVersions != null) {
- for (String uniqueID : allVersions.values()) {
- Either<ComponentMetadataData, TitanOperationStatus> getNodeResult = titanGenericDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueID, ComponentMetadataData.class);
- if (getNodeResult.isRight()) {
- log.error("DB error during while getting component with uniqueID {}, error: {}", uniqueID, getNodeResult.right().value());
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- ComponentMetadataData component = getNodeResult.left().value();
- component.getMetadataDataDefinition().setInvariantUUID(invariantUUID);
- Either<ComponentMetadataData, TitanOperationStatus> updateNodeResult = titanGenericDao.updateNode(component, ComponentMetadataData.class);
- log.debug("updated child invariantUUID {}", updateNodeResult.left().value().getMetadataDataDefinition().getInvariantUUID());
- if (updateNodeResult.isRight()) {
- log.error("DB error during while updating component {}, error: {}", component.getMetadataDataDefinition().getName(), updateNodeResult.right().value());
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- }
- }
- return Either.left(true);
- }
-
- private List<ComponentMetadataData> reduceHighestVersionResourcesList(List<ComponentMetadataData> allHighestVersionResources) {
- List<ComponentMetadataData> resultList = null;
- Map<String, ComponentMetadataData> resultHM = new HashMap<String, ComponentMetadataData>();
- for (ComponentMetadataData resource : allHighestVersionResources) {
- if (resource.getMetadataDataDefinition().getInvariantUUID() != null && !resource.getMetadataDataDefinition().getInvariantUUID().isEmpty()) {
- log.debug("invariantUUID {} ", resource.getMetadataDataDefinition().getInvariantUUID());
- continue;
- }
- String curUUID = resource.getMetadataDataDefinition().getUUID();
- if (resultHM.containsKey(curUUID)) {
- int isHighest = resultHM.get(curUUID).getMetadataDataDefinition().getVersion().compareTo(resource.getMetadataDataDefinition().getVersion());
- if (isHighest > 0) {
- log.debug("version {} is great than {} ", resultHM.get(curUUID).getMetadataDataDefinition().getVersion(), resource.getMetadataDataDefinition().getVersion());
- continue;
- }
- }
- resultHM.put(curUUID, resource);
- }
- resultList = new ArrayList<ComponentMetadataData>(resultHM.values());
- return resultList;
- }
-
- private boolean isNormative(String resourceName) {
- for (int i = 0; i < NORMATIVE_OLD_NAMES.length; ++i) {
- if (NORMATIVE_OLD_NAMES[i].equals(resourceName))
- return true;
- }
- return false;
- }
-
- private Either<Boolean, StorageOperationStatus> changeNormativeTypeName(ResourceMetadataData resource) {
-
- String resourceName = resource.getMetadataDataDefinition().getName();
-
- if (resourceName != null && !resourceName.isEmpty()) {
- log.debug("Found normative type to change - {}", resourceName);
- String oldName = resourceName;
- String[] splitedName = resourceName.split("\\.");
- String newName = splitedName[splitedName.length - 1];
- String newSystemName = ValidationUtils.convertToSystemName(newName);
- String newNormalizedName = ValidationUtils.normaliseComponentName(newName);
- log.debug("Setting name to be {}", newName);
-
- resource.getMetadataDataDefinition().setName(newName);
- log.debug("Setting system name to be {}", newSystemName);
- resource.getMetadataDataDefinition().setSystemName(newSystemName);
- log.debug("Setting normalized name to be {}", newNormalizedName);
- resource.getMetadataDataDefinition().setNormalizedName(newNormalizedName);
- log.debug("Updating tag in metadata to be {}", newName);
- resource.getMetadataDataDefinition().getTags().remove(oldName);
- resource.getMetadataDataDefinition().getTags().add(newName);
-
- log.debug("Creating tag node with name {}", newName);
- TagData tagData = new TagData();
- tagData.setName(newName);
- Either<TagData, TitanOperationStatus> createNode = titanGenericDao.createNode(tagData, TagData.class);
- if (createNode.isRight()) {
- log.error("Error while creating tag node {}, error: {}.", newName, createNode.right().value());
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
-
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(resource, ResourceMetadataData.class);
- if (updateNode.isRight()) {
- log.error("DB error during while updating normative type {}, error: {}", resource.getMetadataDataDefinition().getName(), updateNode.right().value());
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- log.debug("Normative type {} was successfully updated", resource.getMetadataDataDefinition().getName());
- return Either.left(true);
- }
-
- return Either.left(false);
- }
-
- private Either<Boolean, StorageOperationStatus> generateAndSetToscaResourceName(ResourceMetadataData resource, String toscaResourceName) {
- if (toscaResourceName == null) {
- toscaResourceName = CommonBeUtils.generateToscaResourceName(((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).getResourceType().name(), resource.getMetadataDataDefinition().getSystemName());
- }
- Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists = resourceOperation.validateToscaResourceNameExists(toscaResourceName);
- if (validateToscaResourceNameExists.isRight()) {
- StorageOperationStatus storageOperationStatus = validateToscaResourceNameExists.right().value();
- log.error("Couldn't validate toscaResourceName uniqueness - error: {}", storageOperationStatus);
- return Either.right(storageOperationStatus);
- }
- if (validateToscaResourceNameExists.left().value()) {
- log.debug("Setting tosca resource name to be {}", toscaResourceName);
- ((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).setToscaResourceName(toscaResourceName);
- return Either.left(true);
- } else {
- // As agreed with Renana - cannot be fixed automatically
- log.warn("toscaResourceName {} is not unique! Cannot set it. Continuing...");
- return Either.left(false);
- }
- }
-
- public boolean testRemoveHeatPlaceHolders(String appConfigDir) {
-
- if (!AllowMultipleHeats.removeAndUpdateHeatPlaceHolders(titanGenericDao, log, false)) {
- log.error("Failed to update heat place holders");
- return false;
- }
- return true;
- }
-
- private Either<Boolean, StorageOperationStatus> setVfToscaResourceName(ResourceMetadataData resource) {
- String resourceName = resource.getMetadataDataDefinition().getName();
- String resourceType = ((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).getResourceType().name();
- String toscaResourceName = CommonBeUtils.generateToscaResourceName(resourceType, resource.getMetadataDataDefinition().getSystemName());
- log.debug("Setting tosca resource name {} to VF {}", toscaResourceName, resourceName);
- ((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).setToscaResourceName(toscaResourceName);
-
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(resource, ResourceMetadataData.class);
- if (updateNode.isRight()) {
- log.error("DB error during while updating VF tosca resource name {}, error: {}", resource.getMetadataDataDefinition().getName(), updateNode.right().value());
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- log.debug("Tosca resource name of VF {} was successfully updated", resource.getMetadataDataDefinition().getName());
- return Either.left(true);
- }
-
- public boolean testAddGroupUuids(String appConfigDir) {
-
- if (!AddGroupUuid.addGroupUuids(titanGenericDao, log, false)) {
- log.error("Failed to update group UUIDs");
- return false;
- }
- return true;
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/VfcNamingAlignment.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/VfcNamingAlignment.java
deleted file mode 100644
index e488017679..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/VfcNamingAlignment.java
+++ /dev/null
@@ -1,184 +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.migration.v1604;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.openecomp.sdc.be.resources.data.TagData;
-import org.openecomp.sdc.be.utils.CommonBeUtils;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.util.ValidationUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import fj.data.Either;
-
-public class VfcNamingAlignment {
-
- private static Logger log = LoggerFactory.getLogger(VfcNamingAlignment.class.getName());
-
- @Autowired
- protected TitanGenericDao titanGenericDao;
- @Autowired
- protected ResourceOperation resourceOperation;
-
- public boolean alignVfcNames1604(String appConfigDir) {
- log.debug("Started alignVfcNames1604 procedure..");
- log.debug("Getting all resources with resourceType = VFC/CP/VL");
- boolean result = false;
- try {
- Map<String, Object> notProperties = new HashMap<>();
- notProperties.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
- Either<List<ResourceMetadataData>, TitanOperationStatus> allVfcResources = titanGenericDao
- .getByCriteria(NodeTypeEnum.Resource, null, notProperties, ResourceMetadataData.class);
- if (allVfcResources.isRight()) {
- log.error("Couldn't get VFC resources from DB, error: {}", allVfcResources.right().value());
- result = false;
- return result;
- }
- List<ResourceMetadataData> vfcList = allVfcResources.left().value();
- if (vfcList == null) {
- log.error("Couldn't get VFC/CP/VL resources from DB, no resources found");
- result = false;
- return result;
- }
- log.debug("Found {} VFC/CP/VL resources", vfcList.size());
- for (ResourceMetadataData vfc : vfcList) {
- log.debug("Checking resource {}", vfc.getMetadataDataDefinition().getName());
- boolean wasChanged = false;
-
- Either<Boolean, StorageOperationStatus> vfcEither = fixToscaNameEmpty(vfc);
- if (vfcEither.isRight()) {
- log.error("DB error during checkIsToscaNameEmpty - exiting...");
- result = false;
- return result;
- }
- wasChanged = wasChanged | vfcEither.left().value();
-
- vfcEither = fixVfcToscaNameHasVf(vfc);
- if (vfcEither.isRight()) {
- log.error("DB error during checkIsVfcToscaNameHasVf - exiting...");
- result = false;
- return result;
- }
- wasChanged = wasChanged | vfcEither.left().value();
-
- if (wasChanged) {
- Either<ResourceMetadataData, TitanOperationStatus> updateVfc = updateVfc(vfc);
- if (updateVfc.isRight()) {
- log.error("DB error during while updating resource {}, error: {} - exiting...",
- vfc.getMetadataDataDefinition().getName(), updateVfc.right().value());
- result = false;
- return result;
- }
- log.debug("Resource {} was successfully updated", vfc.getMetadataDataDefinition().getName());
- }
-
- }
- result = true;
- } finally {
- if (!result) {
- titanGenericDao.rollback();
- log.debug("**********************************************");
- log.debug("alignVfcNames1604 procedure FAILED!!");
- log.debug("**********************************************");
- } else {
- titanGenericDao.commit();
- log.debug("**********************************************");
- log.debug("alignVfcNames1604 procedure ended successfully!");
- log.debug("**********************************************");
- }
- }
-
- return result;
- }
-
- private Either<ResourceMetadataData, TitanOperationStatus> updateVfc(ResourceMetadataData vfc) {
- return titanGenericDao.updateNode(vfc, ResourceMetadataData.class);
- }
-
- private Either<Boolean, StorageOperationStatus> fixToscaNameEmpty(ResourceMetadataData vfc) {
- String toscaResourceName = ((ResourceMetadataDataDefinition) vfc.getMetadataDataDefinition())
- .getToscaResourceName();
- if (toscaResourceName == null || toscaResourceName.trim().equals(Constants.EMPTY_STRING)) {
- log.debug("Tosca resource name is empty - setting new tosca name...");
- Either<Boolean, StorageOperationStatus> generateAndSetToscaResourceName = generateAndSetToscaResourceName(
- vfc, null);
- if (generateAndSetToscaResourceName.isRight()) {
- return Either.right(generateAndSetToscaResourceName.right().value());
- }
- return Either.left(true);
- }
- return Either.left(false);
- }
-
- private Either<Boolean, StorageOperationStatus> fixVfcToscaNameHasVf(ResourceMetadataData vfc) {
- String toscaResourceName = ((ResourceMetadataDataDefinition) vfc.getMetadataDataDefinition())
- .getToscaResourceName();
- if (toscaResourceName.contains(".vf.")) {
- log.debug("Tosca resource name {} is VF-style - setting new tosca name...", toscaResourceName);
- Either<Boolean, StorageOperationStatus> generateAndSetToscaResourceName = generateAndSetToscaResourceName(
- vfc, null);
- if (generateAndSetToscaResourceName.isRight()) {
- return Either.right(generateAndSetToscaResourceName.right().value());
- }
- return Either.left(true);
- }
- return Either.left(false);
- }
-
- private Either<Boolean, StorageOperationStatus> generateAndSetToscaResourceName(ResourceMetadataData vfc,
- String toscaResourceName) {
- if (toscaResourceName == null) {
- toscaResourceName = CommonBeUtils.generateToscaResourceName(
- ((ResourceMetadataDataDefinition) vfc.getMetadataDataDefinition()).getResourceType().name(),
- vfc.getMetadataDataDefinition().getSystemName());
- }
- Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists = resourceOperation
- .validateToscaResourceNameExists(toscaResourceName);
- if (validateToscaResourceNameExists.isRight()) {
- StorageOperationStatus storageOperationStatus = validateToscaResourceNameExists.right().value();
- log.error("Couldn't validate toscaResourceName uniqueness - error: {}", storageOperationStatus);
- return Either.right(storageOperationStatus);
- }
- if (validateToscaResourceNameExists.left().value()) {
- log.debug("Setting tosca resource name to be {}", toscaResourceName);
- ((ResourceMetadataDataDefinition) vfc.getMetadataDataDefinition()).setToscaResourceName(toscaResourceName);
- return Either.left(true);
- } else {
- // As agreed with Renana - cannot be fixed automatically
- log.warn("toscaResourceName {} is not unique! Cannot set it. Continuing...");
- return Either.left(false);
- }
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1607/CsarMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1607/CsarMigration.java
deleted file mode 100644
index b141eecb87..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1607/CsarMigration.java
+++ /dev/null
@@ -1,93 +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.migration.v1607;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.apache.tinkerpop.gremlin.structure.VertexProperty;
-import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-public class CsarMigration {
- private static Logger log = LoggerFactory.getLogger(CsarMigration.class.getName());
-
- @Autowired
- protected TitanGenericDao titanGenericDao;
-
- public boolean removeCsarResources() {
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao
- .getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
- if (byCriteria.isRight()) {
- log.debug("Failed to fetch VF resources by criteria ", byCriteria.right().value());
- return false;
- }
- List<ResourceMetadataData> resources = byCriteria.left().value();
-
- try {
- for (ResourceMetadataData data : resources) {
- if (data.getMetadataDataDefinition().getCsarUUID() != null) {
- log.debug("VF {} with CSAR {}", data.getUniqueId(), data.getMetadataDataDefinition().getCsarUUID());
- Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao
- .getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), data.getUniqueId());
- if (vertexByProperty.isRight()) {
- log.debug("Failed to fetch vertex with id {} . skip resource {} ", data.getUniqueId(),
- data.getMetadataDataDefinition().getName());
- continue;
- }
- Vertex vertex = vertexByProperty.left().value();
- Iterator<VertexProperty<Object>> properties = vertex
- .properties(GraphPropertiesDictionary.CSAR_UUID.getProperty());
- while (properties.hasNext()) {
- VertexProperty<Object> next = properties.next();
- next.remove();
- }
-
- }
- }
- titanGenericDao.commit();
- } catch (Exception e) {
- log.debug("Failed to clean CSAR UUID. rollback");
- titanGenericDao.rollback();
- }
-
- return true;
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/TitanFixUtils.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/TitanFixUtils.java
deleted file mode 100644
index fedd4d2545..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/TitanFixUtils.java
+++ /dev/null
@@ -1,384 +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.migration.v1610;
-
-import com.google.gson.Gson;
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanVertex;
-import fj.data.Either;
-
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import java.util.*;
-
-public class TitanFixUtils {
- private static Logger log = LoggerFactory.getLogger(TitanFixUtils.class.getName());
-
- @Autowired
- protected TitanGenericDao titanGenericDao;
- @Autowired
- protected CacheMangerOperation cacheMangerOperation;
-
- public boolean fixIconsInNormatives() {
- log.info("starting fix");
- String vlName = "VL";
- String elineName = "VL_ELINE";
- String elineFixedName = "VL ELINE";
- Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
- if (graphResult.isRight()) {
- log.error("failed to get graph object.");
- return false;
- }
-
- boolean operationFailed = false;
- Map<String, Object> vlVerticeProperties = null;
- Map<String, Object> elineVerticeProperties = null;
-
- try {
- TitanGraph titanGraph = graphResult.left().value();
- log.info("look up vl :{}", vlName);
-
- Iterable<TitanVertex> vertices = titanGraph.query()
- .has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName())
- .has(GraphPropertiesDictionary.NAME.getProperty(), vlName)
- .has(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true).vertices();
-
- if (vertices == null) {
- log.error("failed to get vernice for resource name {}", vlName);
- operationFailed = true;
- return false;
- }
-
- Iterator<TitanVertex> iterator = vertices.iterator();
- List<TitanVertex> vertexList = new ArrayList<>();
-
- if (iterator == null) {
- log.error("failed to get iterator over vertices object returned for resource id {}", vlName);
- operationFailed = true;
- return false;
- }
-
- while (iterator.hasNext()) {
- TitanVertex vertex = iterator.next();
- vertexList.add(vertex);
- }
-
- if (!(vertexList.size() == 1)) {
- log.error("failed to get 1 vertex for resource {} with highest true. instead got {}", vlName,
- vertexList.size());
- operationFailed = true;
- return false;
- }
-
- TitanVertex vlVertex = vertexList.get(0);
-
- log.info("look up eline:{}", elineName);
-
- boolean vl_eline_found = true;
-
- vertices = titanGraph.query()
- .has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName())
- .has(GraphPropertiesDictionary.NAME.getProperty(), elineName)
- .has(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true).vertices();
-
- if (vertices == null) {
- log.error("failed to get vertices object returned for resource {}", elineName);
- operationFailed = true;
-
- vl_eline_found = false;
- }
-
- if (vl_eline_found) {
- iterator = vertices.iterator();
- vertexList = new ArrayList<>();
- if (iterator == null) {
- log.error("failed to get iterator over vertices object returned for resource id {}", elineName);
- operationFailed = true;
-
- vl_eline_found = false;
- }
-
- if (vl_eline_found) {
- while (iterator.hasNext()) {
- TitanVertex vertex = iterator.next();
- vertexList.add(vertex);
- }
-
- if (!(vertexList.size() == 1)) {
- log.error("failed to get 1 vertex for resource {} with highest true. instead got {}",
- elineName, vertexList.size());
- operationFailed = true;
-
- vl_eline_found = false;
- }
- }
- }
-
- if (!vl_eline_found) {
- log.info("look up eline:{}", elineFixedName);
- vl_eline_found = true;
- operationFailed = false;
-
- vertices = titanGraph.query()
- .has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName())
- .has(GraphPropertiesDictionary.NAME.getProperty(), elineFixedName)
- .has(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true).vertices();
-
- if (vertices == null) {
- log.error("failed to get vertices object returned for resource {}", elineFixedName);
- operationFailed = true;
-
- vl_eline_found = false;
- }
-
- if (vl_eline_found) {
- iterator = vertices.iterator();
- vertexList = new ArrayList<>();
- if (iterator == null) {
- log.error("failed to get iterator over vertices object returned for resource id {}",
- elineFixedName);
- operationFailed = true;
-
- vl_eline_found = false;
- }
-
- if (vl_eline_found) {
- while (iterator.hasNext()) {
- TitanVertex vertex = iterator.next();
- vertexList.add(vertex);
- }
-
- if (!(vertexList.size() == 1)) {
- log.error("failed to get 1 vertex for resource {} with highest true. instead got {}",
- elineFixedName, vertexList.size());
- operationFailed = true;
-
- vl_eline_found = false;
- }
- }
- }
- }
-
- if (!vl_eline_found) {
- return false;
- } else {
- TitanVertex elineVertex = vertexList.get(0);
-
- vlVerticeProperties = titanGenericDao.getProperties(vlVertex);
-
- log.info("VL Vertice Properties {}", vlVerticeProperties);
- if ("network".equals(vlVerticeProperties.get(GraphPropertiesDictionary.ICON.getProperty()))) {
- log.info("nothing to update in vl");
- } else {
- log.info("updating property icon of vl");
- vlVertex.property(GraphPropertiesDictionary.ICON.getProperty(), "network");
- }
-
- elineVerticeProperties = titanGenericDao.getProperties(elineVertex);
-
- log.info("eline vertice Properties {}", elineVerticeProperties);
- if ("network".equals(elineVerticeProperties.get(GraphPropertiesDictionary.ICON.getProperty()))) {
- log.info("nothing to update in eline");
- } else {
- log.info("updating property icon of eline");
- elineVertex.property(GraphPropertiesDictionary.ICON.getProperty(), "network");
- }
-
- if ("VL ELINE".equals(elineVerticeProperties.get(GraphPropertiesDictionary.NAME.getProperty()))) {
- log.info("nothing to update in eline");
- } else {
- log.info("updating property name and tag of eline");
- elineVertex.property(GraphPropertiesDictionary.NAME.getProperty(), elineFixedName);
- List<String> tags = new ArrayList<>();
- tags.add("VL ELINE");
- elineVertex.property(GraphPropertiesDictionary.TAGS.getProperty(), new Gson().toJson(tags));
- }
-
- log.info("print current properties state");
-
- vlVerticeProperties = titanGenericDao.getProperties(vlVertex);
-
- log.info("vertice vl Properties {}", vlVerticeProperties);
- elineVerticeProperties = titanGenericDao.getProperties(elineVertex);
-
- log.info("vertice eline Properties {}", elineVerticeProperties);
- }
-
- try {
- Thread.sleep(30 * 1000);
- } catch (InterruptedException e) {
- log.error("exception", e);
- }
- return true;
- } finally {
- if (operationFailed) {
- titanGenericDao.rollback();
- } else {
- titanGenericDao.commit();
- long time = System.currentTimeMillis();
- if (vlVerticeProperties != null) {
- cacheMangerOperation.updateComponentInCache(
- (String) vlVerticeProperties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()), time,
- NodeTypeEnum.Resource);
- }
- if (elineVerticeProperties != null) {
- cacheMangerOperation.updateComponentInCache(
- (String) elineVerticeProperties.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty()),
- time, NodeTypeEnum.Resource);
- }
- }
- }
- }
-
- /**
- * in 1610 we encounter an issue that if a capability property overrides a
- * property of a derived capability then it was created with out a property
- * type when it was first imported as part of the capability types. this
- * will add property type to the properties missing it.
- */
- public boolean fixCapabiltyPropertyTypes() {
-
- String propertyIdSecure = "tosca.capabilities.Endpoint.Admin.secure";
- String propertyIdNetworkName = "tosca.capabilities.Endpoint.Public.network_name";
- Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
-
- if (graphResult.isRight()) {
- log.error("failed to get graph object.");
- return false;
- }
-
- boolean operationFailed = false;
- try {
- TitanGraph titanGraph = graphResult.left().value();
- log.info("look up propertyIdSecure:{}", propertyIdSecure);
- Iterable<TitanVertex> vertices = titanGraph.query()
- .has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyIdSecure).vertices();
- if (vertices == null) {
- log.error("failed to get vertices object returned for resource id {}", propertyIdSecure);
- operationFailed = true;
- return false;
- }
- Iterator<TitanVertex> iterator = vertices.iterator();
- List<TitanVertex> vertexList = new ArrayList<>();
-
- if (iterator == null) {
- log.error("failed to get iterator over vertices object returned for resource id {}", propertyIdSecure);
- operationFailed = true;
- return false;
- }
-
- while (iterator.hasNext()) {
- TitanVertex vertex = iterator.next();
- vertexList.add(vertex);
- }
-
- if (vertexList.size() != 1) {
- log.error("failed to get 1 vertex for resource id {} instead got {}", propertyIdSecure,
- vertexList.size());
- operationFailed = true;
- return false;
- }
-
- TitanVertex propertyVerticeSecure = vertexList.get(0);
-
- log.info("look up propertyIdNetworkName:{}", propertyIdNetworkName);
- vertices = titanGraph.query()
- .has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyIdNetworkName).vertices();
- if (vertices == null) {
- log.error("failed to get vertices object returned for resource id {}", propertyIdNetworkName);
- operationFailed = true;
- return false;
- }
-
- iterator = vertices.iterator();
- vertexList = new ArrayList<>();
-
- if (iterator == null) {
- log.error("failed to get iterator over vertices object returned for resource id {}",
- propertyIdNetworkName);
- operationFailed = true;
- return false;
- }
-
- while (iterator.hasNext()) {
- TitanVertex vertex = iterator.next();
- vertexList.add(vertex);
- }
-
- if (!(vertexList.size() == 1)) {
- log.error("failed to get 1 vertex for resource id {} instead got {}", propertyIdNetworkName,
- vertexList.size());
- operationFailed = true;
- return false;
- }
-
- TitanVertex propertyVerticeNetworkName = vertexList.get(0);
-
- Map<String, Object> verticeNetworkNameProperties = titanGenericDao
- .getProperties(propertyVerticeNetworkName);
-
- log.info("vertice NetworkName Properties {}", verticeNetworkNameProperties);
- Object type = verticeNetworkNameProperties.get(GraphPropertiesDictionary.TYPE.getProperty());
- if (type == null || "".equals(type)) {
- log.info("updating property Vertice Network Name");
- propertyVerticeNetworkName.property(GraphPropertiesDictionary.TYPE.getProperty(), "string");
- }
-
- Map<String, Object> verticeSecureProperties = titanGenericDao.getProperties(propertyVerticeSecure);
-
- log.info("vertice Secure Properties {}", verticeSecureProperties);
-
- type = verticeSecureProperties.get(GraphPropertiesDictionary.TYPE.getProperty());
-
- if (type == null || "".equals(type)) {
- log.info("updating property Vertice Secure");
- propertyVerticeSecure.property(GraphPropertiesDictionary.TYPE.getProperty(), "boolean");
- }
-
- log.info("print current properties state");
-
- verticeNetworkNameProperties = titanGenericDao.getProperties(propertyVerticeNetworkName);
-
- log.info("vertice NetworkName Properties {}", verticeNetworkNameProperties);
-
- verticeSecureProperties = titanGenericDao.getProperties(propertyVerticeSecure);
-
- log.info("vertice Secure Properties {}", verticeSecureProperties);
-
- return true;
- } finally {
- if (operationFailed) {
- titanGenericDao.rollback();
- } else {
- titanGenericDao.commit();
- }
- }
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/ToscaArtifactsAlignment.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/ToscaArtifactsAlignment.java
deleted file mode 100644
index 673190e8c1..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1610/ToscaArtifactsAlignment.java
+++ /dev/null
@@ -1,461 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.asdctool.impl.migration.v1610;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.collections.MapUtils;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-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.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.AbstractOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.resources.data.ArtifactData;
-import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
-import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.util.StreamUtils;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import fj.data.Either;
-
-/**
- * This Class holds the logic to add Tosca Artifacts placeholder and payload.<br>
- * This addition is done for old version of Services and Resources (pre 1610) that weren't created with them.<br>
- *
- * @author mshitrit <br>
- *
- *
- */
-public class ToscaArtifactsAlignment extends AbstractOperation {
- @Autowired
- private IArtifactOperation artifactOperation;
-
- @Autowired
- private ServiceBusinessLogic serviceBusinessLogic;
-
- private static Logger log = LoggerFactory.getLogger(ToscaArtifactsAlignment.class.getName());
-
- private static final String ERROR_PREFIX = "Tosca Artifact Alignment Error: ";
-
- // API that Fetches Resource
- private final Function<ComponentMetadataData, Resource> resourceFetcher = componentMD -> getComponent(componentMD, ComponentTypeEnum.RESOURCE);
- // API that Fetches Service
- private final Function<ComponentMetadataData, Service> serviceFetcher = componentMD -> getComponent(componentMD, ComponentTypeEnum.SERVICE);
- // Class Getters
- private final Supplier<Class<ResourceMetadataData>> resourceClassGetter = () -> ResourceMetadataData.class;
- private final Supplier<Class<ServiceMetadataData>> serviceClassGetter = () -> ServiceMetadataData.class;
-
- /**
- * This method holds the logic to add Tosca Artifacts placeholder and payload.<br>
- *
- * @return true if succeed otherwise returns false
- */
- public boolean alignToscaArtifacts() {
- Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>();
- List<ResourceMetadataData> allResources = new ArrayList<>();
- List<ResourceMetadataData> resourcesWithoutToscaPlaceHolder = new ArrayList<>();
- List<ServiceMetadataData> allServices = new ArrayList<>();
- List<ServiceMetadataData> servicesWithoutToscaPlaceHolder = new ArrayList<>();
- log.debug("alignToscaArtifacts Start");
- try {
-
- if (errorWrapper.isEmpty()) {
- log.info("Fetching all resources");
- fillAllComponetOfSpecificType(allResources, NodeTypeEnum.Resource, resourceClassGetter, errorWrapper);
- }
-
- if (errorWrapper.isEmpty()) {
- // Filter Resources Without Tosca Artifacts
- log.info("filtering resources to add tosca placeholder");
- Either<List<ResourceMetadataData>, TitanOperationStatus> eitherRelevantResources = getComponentsWithMissingToscaArtifacts(resourceClassGetter, NodeTypeEnum.Resource, allResources);
- fillListOrWrapper(errorWrapper, resourcesWithoutToscaPlaceHolder, eitherRelevantResources);
- }
-
- if (errorWrapper.isEmpty()) {
- // Add PlaceHolders To Resources
- log.info("adding tosca placeholders artifacts to resources");
- addToscaArtifactToComponents(resourcesWithoutToscaPlaceHolder, resourceFetcher, NodeTypeEnum.Resource, errorWrapper);
- }
- if (errorWrapper.isEmpty()) {
- // Add payload to Resources
- log.info("generating payload to tosca artifacts on resources");
- fillResourcesPayload(allResources, errorWrapper);
- }
-
- if (errorWrapper.isEmpty()) {
- log.info("Fetching all services");
- fillAllComponetOfSpecificType(allServices, NodeTypeEnum.Service, serviceClassGetter, errorWrapper);
- }
- if (errorWrapper.isEmpty()) {
- // Filter Services Without Tosca Artifacts
- log.info("filtering services to add tosca placeholder");
- Either<List<ServiceMetadataData>, TitanOperationStatus> eitherRelevantServices = getComponentsWithMissingToscaArtifacts(serviceClassGetter, NodeTypeEnum.Service, allServices);
- fillListOrWrapper(errorWrapper, servicesWithoutToscaPlaceHolder, eitherRelevantServices);
- }
-
- if (errorWrapper.isEmpty()) {
- // Add PlaceHolders To Services
- log.info("adding tosca placeholders artifacts to services");
- addToscaArtifactToComponents(servicesWithoutToscaPlaceHolder, serviceFetcher, NodeTypeEnum.Service, errorWrapper);
- }
-
- if (errorWrapper.isEmpty()) {
- // Filter Services for Payload Add
- // Add payload to Services
- log.info("generating payload to tosca artifacts on services");
- fillToscaArtifactPayload(allServices, serviceFetcher, errorWrapper);
- }
- } finally {
- titanGenericDao.commit();
- }
- return errorWrapper.isEmpty();
-
- }
-
- private void fillResourcesPayload(List<ResourceMetadataData> allResources, Wrapper<TitanOperationStatus> errorWrapper) {
- if (errorWrapper.isEmpty()) {
- // First Only Non VF (CP, VL & VFC)
- List<ResourceMetadataData> basicResources = allResources.stream().filter(e -> isBasicResource((ResourceMetadataDataDefinition) e.getMetadataDataDefinition())).collect(Collectors.toList());
- // Filter resources for Payload Add
- // Add payload to resources
- fillToscaArtifactPayload(basicResources, resourceFetcher, errorWrapper);
- }
- if (errorWrapper.isEmpty()) {
- // VFs
- List<ResourceMetadataData> complexResource = allResources.stream().filter(e -> ((ResourceMetadataDataDefinition) e.getMetadataDataDefinition()).getResourceType() == ResourceTypeEnum.VF).collect(Collectors.toList());
- // Filter resources for Payload Add
- // Add payload to resources
- fillToscaArtifactPayload(complexResource, resourceFetcher, errorWrapper);
- }
- }
-
- private boolean isBasicResource(ResourceMetadataDataDefinition resourceMetadataDataDefinition) {
- final ResourceTypeEnum resourceType = resourceMetadataDataDefinition.getResourceType();
- boolean isBasicResource = resourceType == ResourceTypeEnum.CP || resourceType == ResourceTypeEnum.VL || resourceType == ResourceTypeEnum.VFC;
- return isBasicResource;
- }
-
- private <T extends ComponentMetadataData> void fillAllComponetOfSpecificType(List<T> components, NodeTypeEnum nodeType, Supplier<Class<T>> classGetter, Wrapper<TitanOperationStatus> errorWrapper) {
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.IS_DELETED.getProperty(), true);
- Either<List<T>, TitanOperationStatus> eitherComponentMD = titanGenericDao.getByCriteria(nodeType, null, props, classGetter.get());
- if (eitherComponentMD.isLeft()) {
- components.addAll(eitherComponentMD.left().value());
- } else {
- final TitanOperationStatus errorType = eitherComponentMD.right().value();
- if (errorType != TitanOperationStatus.NOT_FOUND) {
- log.error("{} When fetching all components of type:{} a titan error occured:{}", ERROR_PREFIX, nodeType.getName(), errorType.name());
- errorWrapper.setInnerElement(errorType);
- }
- }
-
- }
-
- private <T extends ComponentMetadataData, R extends Component> void addToscaArtifactToComponents(List<T> relevantResources, Function<ComponentMetadataData, R> componentConvertor, NodeTypeEnum nodeType,
- Wrapper<TitanOperationStatus> errorWrapper) {
-
- // This Stream contains all create tosca placeholder results
- Stream<StorageOperationStatus> addToscaToComponentsResultsStream = relevantResources.stream().map(e -> addToscaArtifacts(e, nodeType, componentConvertor));
- // Execute the stream, and collect error
- Optional<StorageOperationStatus> optionalError = addToscaToComponentsResultsStream.filter(e -> e != StorageOperationStatus.OK).findFirst();
-
- // Handle error
- if (optionalError.isPresent()) {
- errorWrapper.setInnerElement(TitanOperationStatus.NOT_CREATED);
- }
- }
-
- private <R extends Component> R getComponent(ComponentMetadataData md, ComponentTypeEnum componentTypeEnum) {
- R result = null;
- Either<R, StorageOperationStatus> eitherComponent = serviceBusinessLogic.getComponent(md.getMetadataDataDefinition().getUniqueId(), componentTypeEnum);
- if (eitherComponent.isRight()) {
- log.error("{} When fetching component {} of type:{} with uniqueId:{}", ERROR_PREFIX, md.getMetadataDataDefinition().getName(), componentTypeEnum.getValue(), md.getMetadataDataDefinition().getUniqueId());
- } else {
- result = eitherComponent.left().value();
- }
- return result;
- }
-
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifactsWithLog(Component component, User user, boolean isInCertificationRequest, boolean inTransaction, boolean shouldLock) {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> ret;
- try {
- ret = serviceBusinessLogic.populateToscaArtifacts(component, user, isInCertificationRequest, inTransaction, shouldLock);
- if (ret.isLeft()) {
- log.debug("Added payload to tosca artifacts of component {} of type:{} with uniqueId:{}", component.getName(), component.getComponentType().getValue(), component.getUniqueId());
- }
- return ret;
- } catch (Exception e) {
- log.error("{} Exception Occured When filling tosca artifact payload for component {} of type:{} with uniqueId:{}", ERROR_PREFIX, component.getName(), component.getComponentType().name(), component.getUniqueId(), e);
- throw e;
- }
- }
-
- private <R extends Component, T extends ComponentMetadataData> void fillToscaArtifactPayload(List<T> relevantComponents, Function<ComponentMetadataData, R> componentCreator, Wrapper<TitanOperationStatus> errorWrapper) {
-
- final User dummyUser = buildDummyUser();
- // Stream for all fill payload results
- Stream<ImmutablePair<Component, Either<Either<ArtifactDefinition, Operation>, ResponseFormat>>>
- // Filter elements that needs generation of tosca payload
- fillToscaPayloadResultsStream = relevantComponents.stream().filter(e -> isGenerateToscaPayload(e))
- // Converts ComponentMetadataData to Component
- .map(e -> componentCreator.apply(e))
- // For each component generate payload for tosca
- // artifacts
- .map(component -> {
- return new ImmutablePair<Component, Either<Either<ArtifactDefinition, Operation>, ResponseFormat>>(component, populateToscaArtifactsWithLog(component, dummyUser, true, true, false));
- });
-
- try {
- // execute and the stream
- Optional<Component> optionalError = fillToscaPayloadResultsStream.
- // filter in error
- filter(e -> e.getRight().isRight())
- // convert the result to error and execute the stream
- .map(e -> e.getLeft()).findFirst();
-
- // Check if error occurred
- if (optionalError.isPresent()) {
- Component component = optionalError.get();
- log.error("{} When filling tosca artifact payload for component {} of type:{} with uniqueId:{}", ERROR_PREFIX, component.getName(), component.getComponentType().name(), component.getUniqueId());
-
- errorWrapper.setInnerElement(TitanOperationStatus.GENERAL_ERROR);
- }
- } catch (Exception e) {
- log.error("{} When filling tosca artifact payload for components : {}", ERROR_PREFIX, e.getMessage(), e);
- errorWrapper.setInnerElement(TitanOperationStatus.GENERAL_ERROR);
- }
- }
-
- private <R extends Component> StorageOperationStatus addToscaArtifacts(ComponentMetadataData component, NodeTypeEnum nodeType, Function<ComponentMetadataData, R> componentCreator) {
-
- StorageOperationStatus result = StorageOperationStatus.OK;
- R componentDefinition = componentCreator.apply(component);
-
- // Fetch artifacts to be Added
- Either<List<ArtifactDefinition>, StorageOperationStatus> eitherToscaArtifacts = getToscaArtifactsToAdd(componentDefinition);
- if (eitherToscaArtifacts.isRight()) {
- result = eitherToscaArtifacts.right().value();
- } else {
- List<ArtifactDefinition> toscaArtifactsToAdd = eitherToscaArtifacts.left().value();
- if (!CollectionUtils.isEmpty(eitherToscaArtifacts.left().value())) {
- final Stream<ImmutablePair<ArtifactDefinition, Either<ArtifactDefinition, StorageOperationStatus>>> createdToscaPlaceHolderStream = toscaArtifactsToAdd.stream()
- // creates the artifact in the graph
- .map(artifactDef -> new ImmutablePair<ArtifactDefinition, Either<ArtifactDefinition, StorageOperationStatus>>(artifactDef,
- artifactOperation.addArifactToComponent(artifactDef, componentDefinition.getUniqueId(), nodeType, false, true)));
-
- // Execute the stream, and collect error
- Optional<ImmutablePair<ArtifactDefinition, StorageOperationStatus>> optionalError = createdToscaPlaceHolderStream.filter(e -> e.getRight().isRight()).map(e -> new ImmutablePair<>(e.getLeft(), e.getRight().right().value()))
- .findFirst();
-
- // In case error occurred
- if (optionalError.isPresent()) {
- ArtifactDefinition toscaArtifact = optionalError.get().getLeft();
- StorageOperationStatus storageError = optionalError.get().getRight();
- log.error("{} When adding tosca artifact of type {} to component {} of type:{} with uniqueId:{} a storageError occurred:{}", ERROR_PREFIX, toscaArtifact.getArtifactType(), component.getMetadataDataDefinition().getName(),
- nodeType.getName(), component.getMetadataDataDefinition().getUniqueId(), storageError.name());
-
- result = storageError;
- } else {
- log.debug("Added tosca artifacts to component {} of type:{} with uniqueId:{}", component.getMetadataDataDefinition().getName(), nodeType.getName(), component.getMetadataDataDefinition().getUniqueId());
- }
-
- }
- }
-
- return result;
- }
-
- private <R extends Component> Either<List<ArtifactDefinition>, StorageOperationStatus> getToscaArtifactsToAdd(R componentDefinition) {
-
- Either<List<ArtifactDefinition>, StorageOperationStatus> result;
- List<ArtifactDefinition> toscaArtifactsAlreadyExist = new ArrayList<>();
- if (!MapUtils.isEmpty(componentDefinition.getToscaArtifacts())) {
- toscaArtifactsAlreadyExist.addAll(componentDefinition.getToscaArtifacts().values());
- }
-
- // Set Tosca Artifacts on component
- serviceBusinessLogic.setToscaArtifactsPlaceHolders(componentDefinition, buildDummyUser());
-
- List<ArtifactDefinition> toscaArtifactsToAdd = new ArrayList<>();
- if (!MapUtils.isEmpty(componentDefinition.getToscaArtifacts())) {
- final Collection<ArtifactDefinition> allToscaArtifacts = componentDefinition.getToscaArtifacts().values();
- Set<String> artifactTypesExist = toscaArtifactsAlreadyExist.stream().map(e -> e.getArtifactType()).collect(Collectors.toSet());
- toscaArtifactsToAdd = allToscaArtifacts.stream().filter(e -> !artifactTypesExist.contains(e.getArtifactType())).collect(Collectors.toList());
- result = Either.left(toscaArtifactsToAdd);
- } else {
- log.error("{} failed to add tosca artifacts in bussiness logic to component {} of type:{} with uniqueId:{}", ERROR_PREFIX, componentDefinition.getName(), componentDefinition.getComponentType().getValue(),
- componentDefinition.getUniqueId());
- result = Either.right(StorageOperationStatus.ARTIFACT_NOT_FOUND);
- }
- return result;
- }
-
- private User buildDummyUser() {
- User user = new User();
- user.setUserId("migrationTask");
- return user;
- }
-
- private boolean isGenerateToscaPayload(ComponentMetadataData component) {
- final String state = component.getMetadataDataDefinition().getState();
- boolean componentLifeCycleStateIsValid = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.name().equals(state) || LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name().equals(state);
-
- return !componentLifeCycleStateIsValid;
-
- }
-
- private <T> void fillListOrWrapper(Wrapper<TitanOperationStatus> wrapper, List<T> listToFill, Either<List<T>, TitanOperationStatus> either) {
- if (either.isRight()) {
- final TitanOperationStatus errorType = either.right().value();
- if (errorType != TitanOperationStatus.NOT_FOUND) {
- wrapper.setInnerElement(errorType);
- }
- } else {
- listToFill.addAll(either.left().value());
- }
- }
-
- private <T extends ComponentMetadataData> Either<List<T>, TitanOperationStatus> getComponentsWithMissingToscaArtifacts(Supplier<Class<T>> classGetter, NodeTypeEnum nodeType, List<T> allComponents) {
-
- Either<List<T>, TitanOperationStatus> result;
- Stream<ImmutablePair<T, Either<List<ArtifactData>, TitanOperationStatus>>> componentsWithToscaStream =
- // Create a Stream of pairs : component and its Tosca Artifacts
- allComponents.stream().map(e -> new ImmutablePair<>(e, getToscaArtifatcs(e, nodeType)));
-
- List<ImmutablePair<T, Either<List<ArtifactData>, TitanOperationStatus>>> componentsWithToscaArtifacts =
- // Collect the stream to list.
- // in case getToscaArtifatcs failed, the first failure is
- // added to the list
- // (the collection stops after first failure)
- StreamUtils.takeWhilePlusOneNoEval(componentsWithToscaStream, e -> e.getRight().isLeft()).collect(Collectors.toList());
-
- // retrieve the failure optional (it may or may not exist)
- Optional<TitanOperationStatus> isErrorOccured = componentsWithToscaArtifacts.stream()
- // convert to the right side of the pair of type Either
- .map(e -> e.getRight())
- // Filter in only the errors
- .filter(e -> e.isRight()).
- // map the error from Either to TitanOperationStatus
- map(e -> e.right().value()).findFirst();
-
- // In case failure occurred
- if (isErrorOccured.isPresent()) {
- result = Either.right(isErrorOccured.get());
- // In case NO failure occurred
- } else {
- List<T> filteredComponents = componentsWithToscaArtifacts.stream()
- // Filter in only elements that does NOT have tosca
- // artifacts
- .filter(e -> isNotContainAllToscaArtifacts(e))
- // Convert back to Components List & collect
- .map(e -> e.getLeft()).collect(Collectors.toList());
-
- result = Either.left(filteredComponents);
- }
-
- return result;
- }
-
- private <T extends ComponentMetadataData> boolean isNotContainAllToscaArtifacts(ImmutablePair<T, Either<List<ArtifactData>, TitanOperationStatus>> pair) {
-
- final List<ArtifactData> artifactList = pair.getRight().left().value();
-
- Set<ArtifactTypeEnum> filteredToscaList = artifactList.stream().
- // Convert to ArtifactDataDefinition
- map(e -> e.getArtifactDataDefinition()).
- // Filter in Only Tosca Artifacts
- filter(e -> e.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA).
- // Convert To ArtifactTypeEnum
- map(e -> ArtifactTypeEnum.findType(e.getArtifactType())).
- // Filter Out nulls in case of Type not found
- filter(e -> e != null).collect(Collectors.toSet());
-
- boolean toscaArifactContained = filteredToscaList.contains(ArtifactTypeEnum.TOSCA_CSAR) && filteredToscaList.contains(ArtifactTypeEnum.TOSCA_TEMPLATE);
- return !toscaArifactContained;
- }
-
- private <T extends ComponentMetadataData> Either<List<ArtifactData>, TitanOperationStatus> getToscaArtifatcs(T component, NodeTypeEnum nodeType) {
-
- Either<List<ArtifactData>, TitanOperationStatus> result;
- // All The Artifacts of the Component
- Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> eitherComponentArtifacts = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), component.getMetadataDataDefinition().getUniqueId(),
- GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class);
-
- if (eitherComponentArtifacts.isLeft()) {
- // Convert Artifact Edge Pair to Artifact
- List<ArtifactData> toscaArtifacts = eitherComponentArtifacts.left().value().stream()
- // map ImmutablePair<ArtifactData, GraphEdge> to
- // ArtifactData
- .map(e -> e.getLeft())
- // Filter in only Tosca Artifacts
- .filter(artifact -> artifact.getArtifactDataDefinition().getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA)
- // Collect
- .collect(Collectors.toList());
- result = Either.left(toscaArtifacts);
- } else if (eitherComponentArtifacts.right().value() == TitanOperationStatus.NOT_FOUND) {
- result = Either.left(new ArrayList<>());
- } else {
- final TitanOperationStatus titanError = eitherComponentArtifacts.right().value();
- log.error("{} When fetching artifacts for component {} of type:{} with uniqueId:{} a titanError occurred:{}", ERROR_PREFIX, component.getMetadataDataDefinition().getName(), nodeType.getName(),
- component.getMetadataDataDefinition().getUniqueId(), titanError.name());
-
- result = Either.right(titanError);
- }
-
- return result;
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/DataTypesUpdate.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/DataTypesUpdate.java
deleted file mode 100644
index d7f36840c7..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/DataTypesUpdate.java
+++ /dev/null
@@ -1,428 +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.migration.v1702;
-
-import java.io.File;
-import java.io.FileReader;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.components.impl.ImportUtils;
-import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
-import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
-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.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
-import org.openecomp.sdc.be.resources.data.PropertyData;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.yaml.snakeyaml.Yaml;
-
-import fj.data.Either;
-
-/**
- * Allows to update existing or create new data types according input file (yaml)
- * @author ns019t
- *
- */
-public class DataTypesUpdate {
-
- private static Logger log = LoggerFactory.getLogger(Migration1702.class.getName());
-
- @Autowired
- private PropertyOperation propertyOperation;
- @Autowired
- private ComponentsUtils componentsUtils;
-
- @SuppressWarnings("unchecked")
- /**
- * Updates existing or creates new data types according input file (yaml)
- * @param dataTypeYmlFilePath
- * @return
- */
- public boolean updateDataTypes(String dataTypeYmlFilePath) {
-
-
- List<String> dataTypesToUpdate = new ArrayList<>();
- dataTypesToUpdate.add("org.openecomp.datatypes.EcompHoming");
- dataTypesToUpdate.add("org.openecomp.datatypes.EcompNaming");
- dataTypesToUpdate.add("org.openecomp.datatypes.network.NetworkAssignments");
- dataTypesToUpdate.add("org.openecomp.datatypes.network.ProviderNetwork");
- dataTypesToUpdate.add("org.openecomp.datatypes.network.NetworkFlows");
- dataTypesToUpdate.add("org.openecomp.datatypes.Artifact");
- dataTypesToUpdate.add("org.openecomp.datatypes.network.VlanRequirements");
- dataTypesToUpdate.add("org.openecomp.datatypes.network.IpRequirements");
- dataTypesToUpdate.add("org.openecomp.datatypes.network.MacAssignments");
- dataTypesToUpdate.add("org.openecomp.datatypes.network.MacRequirements");
- dataTypesToUpdate.add("org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairIp");
- dataTypesToUpdate.add("org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.MacAddress");
- dataTypesToUpdate.add("org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.Properties");
- dataTypesToUpdate.add("org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPair");
- dataTypesToUpdate.add("org.openecomp.datatypes.heat.contrailV2.virtual.machine.subInterface.AddressPairs");
-
- boolean isSuccessful = true;
- List<DataTypeDefinition> dataTypes = extractDataTypesFromYaml(dataTypeYmlFilePath);
-
- if(CollectionUtils.isEmpty(dataTypes)){
- isSuccessful = false;
- }
-
- List<ImmutablePair<DataTypeDefinition, Boolean>> createdElementTypes = new ArrayList<>();
-
- Iterator<DataTypeDefinition> elementTypeItr = dataTypes.iterator();
- if(isSuccessful ){
- try {
- while (elementTypeItr.hasNext()) {
- DataTypeDefinition elementType = elementTypeItr.next();
- String elementName = elementType.getName();
- Either<ActionStatus, ResponseFormat> validateElementType = validateDataType(elementType);
- if (validateElementType.isRight()) {
- log.debug("Failed to validate data type {}. Status is {}. ", elementName, validateElementType.right().value());
- isSuccessful = false;
- break;
- }
- log.debug("Going to get data type by name {}. ", elementName);
- Either<DataTypeDefinition, StorageOperationStatus> findElementType = propertyOperation.getDataTypeByNameWithoutDerived(elementName);
- if (findElementType.isRight()) {
- StorageOperationStatus status = findElementType.right().value();
- if (status != StorageOperationStatus.NOT_FOUND) {
- log.debug("Failed to fetch data type {}. Status is {}. ", elementName , validateElementType.right().value());
- isSuccessful = false;
- break;
- } else {
- log.debug("Going to add data type with name {}. ", elementName);
- Either<DataTypeDefinition, StorageOperationStatus> dataModelResponse = propertyOperation.addDataType(elementType);
-
- if (dataModelResponse.isRight()) {
- if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
- log.debug("Failed to add data type {}. Status is {}. ", elementName , dataModelResponse.right().value());
- isSuccessful = false;
- break;
- } else {
- createdElementTypes.add(new ImmutablePair<DataTypeDefinition, Boolean>(elementType, false));
- }
- } else {
- createdElementTypes.add(new ImmutablePair<DataTypeDefinition, Boolean>(elementType, true));
- }
-
- }
- } else {
- log.debug("Going to update data type with name {}. ", elementName);
- Either<DataTypeDefinition, StorageOperationStatus> updateDataTypeRes = propertyOperation.updateDataType(elementType, findElementType.left().value());
- if (updateDataTypeRes.isRight()) {
- StorageOperationStatus status = updateDataTypeRes.right().value();
- if (status == StorageOperationStatus.OK) {
- createdElementTypes.add(new ImmutablePair<DataTypeDefinition, Boolean>(elementType, false));
- } else {
- log.debug("Failed to update data type {}. Status is {}. ", elementName , updateDataTypeRes.right().value());
- isSuccessful = false;
- break;
- }
- } else {
- createdElementTypes.add(new ImmutablePair<DataTypeDefinition, Boolean>(elementType, true));
- }
- }
- }
- } finally {
- if(isSuccessful){
- propertyOperation.getTitanGenericDao().commit();
- }else{
- propertyOperation.getTitanGenericDao().rollback();
- }
- }
- }
- return isSuccessful;
- }
-
- @SuppressWarnings("unchecked")
- static public List<DataTypeDefinition> extractDataTypesFromYaml(String dataTypeYmlFilePath) {
- String dataTypeName;
- List<DataTypeDefinition> dataTypes = new ArrayList<>();
- try {
- File file = new File(dataTypeYmlFilePath);
- FileReader fr = new FileReader(file);
- Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(fr);
-
- Iterator<Entry<String, Object>> elementTypesEntryItr = toscaJson.entrySet().iterator();
- while (elementTypesEntryItr.hasNext()) {
- Entry<String, Object> elementTypeNameDataEntry = elementTypesEntryItr.next();
- dataTypeName = elementTypeNameDataEntry.getKey();
- Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue();
-
- DataTypeDefinition dataType = new DataTypeDefinition();
- dataType.setName(dataTypeName);
-
- if (elementTypeJsonData != null) {
-
- if (elementTypeJsonData.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
- dataType.setDescription( (String)elementTypeJsonData.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
- }
- if (elementTypeJsonData.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) {
- dataType.setDerivedFromName( (String)elementTypeJsonData.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
- }
- List<PropertyDefinition> properties = getProperties(elementTypeJsonData);
- if (elementTypeJsonData.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
- dataType.setProperties(properties);
- }
- }
- dataTypes.add(dataType);
- }
-
- } catch (Exception e) {
- log.debug("Failed to extract data types from Yaml file {}. ", dataTypeYmlFilePath);
- e.printStackTrace();
- }
- return dataTypes;
- }
-
- static public List<PropertyDefinition> getProperties(Map<String, Object> toscaJson) {
- List<PropertyDefinition> values = null;
- Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(toscaJson);
-
- if (properties.isLeft()) {
- values = new ArrayList<>();
- Map<String, PropertyDefinition> propertiesMap = properties.left().value();
- if (propertiesMap != null && propertiesMap.isEmpty() == false) {
-
- for (Entry<String, PropertyDefinition> entry : propertiesMap.entrySet()) {
- String propName = entry.getKey();
- PropertyDefinition propertyDefinition = entry.getValue();
- PropertyDefinition newPropertyDefinition = new PropertyDefinition(propertyDefinition);
- newPropertyDefinition.setName(propName);
- values.add(newPropertyDefinition);
- }
- }
- }
-
- return values;
- }
-
- private Either<ActionStatus, ResponseFormat> validateDataType(DataTypeDefinition dataType) {
-
- String dataTypeName = dataType.getName();
- List<PropertyDefinition> properties = dataType.getProperties();
- if (properties == null) {
- // At least one parameter should be defined either in the properties
- // section or at one of the parents
- String derivedDataType = dataType.getDerivedFromName();
- // If there are no properties, then we can create a data type if it
- // is an abstract one or it derives from non abstract data type
- if ((derivedDataType == null || derivedDataType.isEmpty())) {
- if (false == isAbstract(dataType.getName())) {
- if (false == ToscaPropertyType.isScalarType(dataTypeName)) {
- log.debug("Data type {} must have properties unless it derives from non abstract data type",dataType.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
-
- return Either.right(responseFormat);
- }
- }
- } else {
- // if it is not a scalar data type and it derives from abstract
- // data type, we should reject the request.
- if (false == ToscaPropertyType.isScalarType(dataTypeName) && true == isAbstract(derivedDataType)) {
- log.debug("Data type {} which derived from abstract data type must have at least one property",dataType.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
-
- return Either.right(responseFormat);
- }
- }
- } else {
- // properties tag cannot be empty
- if (properties.isEmpty()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null);
-
- return Either.right(responseFormat);
- }
-
- // check no duplicates
- Set<String> collect = properties.stream().map(p -> p.getName()).collect(Collectors.toSet());
- if (collect != null) {
- if (properties.size() != collect.size()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null);
-
- return Either.right(responseFormat);
- }
- }
-
- List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(p -> p.getName()).collect(Collectors.toList());
- if (propertiesWithSameTypeAsDataType != null && propertiesWithSameTypeAsDataType.isEmpty() == false) {
- log.debug("The data type {} contains properties with the type {}",dataType.getName(),dataType.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType, propertiesWithSameTypeAsDataType);
-
- return Either.right(responseFormat);
- }
- }
-
- String derivedDataType = dataType.getDerivedFromName();
- if (derivedDataType != null) {
- Either<DataTypeDefinition, StorageOperationStatus> derivedDataTypeByName = propertyOperation.getDataTypeByName(derivedDataType, true);
- if (derivedDataTypeByName.isRight()) {
- StorageOperationStatus status = derivedDataTypeByName.right().value();
- if (status == StorageOperationStatus.NOT_FOUND) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null);
-
- return Either.right(responseFormat);
- } else {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.GENERAL_ERROR, dataType, null);
-
- return Either.right(responseFormat);
-
- }
- } else {
-
- DataTypeDefinition derivedDataTypeDef = derivedDataTypeByName.left().value();
- if (properties != null && properties.isEmpty() == false) {
-
- if (true == isScalarType(derivedDataTypeDef)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null);
-
- return Either.right(responseFormat);
- }
-
- Set<String> allParentsProps = new HashSet<>();
- do {
- List<PropertyDefinition> currentParentsProps = derivedDataTypeDef.getProperties();
- if (currentParentsProps != null) {
- for (PropertyDefinition propertyDefinition : currentParentsProps) {
- allParentsProps.add(propertyDefinition.getName());
- }
- }
- derivedDataTypeDef = derivedDataTypeDef.getDerivedFrom();
- } while (derivedDataTypeDef != null);
-
- // Check that no property is already defined in one of the
- // ancestors
- Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet());
- if (alreadyExistPropsCollection != null && alreadyExistPropsCollection.isEmpty() == false) {
- List<String> duplicateProps = new ArrayList<>();
- duplicateProps.addAll(alreadyExistPropsCollection);
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps);
-
- return Either.right(responseFormat);
- }
-
- }
- }
- }
- return Either.left(ActionStatus.OK);
- }
-
- private boolean isAbstract(String dataTypeName) {
-
- ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName);
-
- return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == true;
-
- }
-
- private boolean isScalarType(DataTypeDefinition dataTypeDef) {
-
- boolean isScalar = false;
- DataTypeDefinition dataType = dataTypeDef;
-
- while (dataType != null) {
-
- String name = dataType.getName();
- if (ToscaPropertyType.isScalarType(name)) {
- isScalar = true;
- break;
- }
-
- dataType = dataType.getDerivedFrom();
- }
-
- return isScalar;
- }
-
-// public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition) {
-//
-// Either<DataTypeDefinition, StorageOperationStatus> result = null;
-//
-// try {
-//
-// List<PropertyDefinition> newProperties = newDataTypeDefinition.getProperties();
-//
-// List<PropertyDefinition> oldProperties = oldDataTypeDefinition.getProperties();
-//
-// String newDerivedFromName = getDerivedFromName(newDataTypeDefinition);
-//
-// String oldDerivedFromName = getDerivedFromName(oldDataTypeDefinition);
-//
-// String dataTypeName = newDataTypeDefinition.getName();
-//
-// List<PropertyDefinition> propertiesToAdd = new ArrayList<>();
-// if (isPropertyOmitted(newProperties, oldProperties, dataTypeName) || isPropertyTypeChanged(dataTypeName, newProperties, oldProperties, propertiesToAdd) || isDerivedFromNameChanged(dataTypeName, newDerivedFromName, oldDerivedFromName)) {
-//
-// log.debug("The new data type " + dataTypeName + " is invalid.");
-//
-// result = Either.right(StorageOperationStatus.CANNOT_UPDATE_EXISTING_ENTITY);
-// return result;
-// }
-//
-// if (propertiesToAdd == null || propertiesToAdd.isEmpty()) {
-// log.debug("No new properties has been defined in the new data type " + newDataTypeDefinition);
-// result = Either.right(StorageOperationStatus.OK);
-// return result;
-// }
-//
-// Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToDataType = addPropertiesToDataType(oldDataTypeDefinition.getUniqueId(), propertiesToAdd);
-//
-// if (addPropertiesToDataType.isRight()) {
-// log.debug("Failed to update data type {} to Graph. Status is {}", oldDataTypeDefinition, addPropertiesToDataType.right().value().name());
-// BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("UpdateDataType", "Property");
-// result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertiesToDataType.right().value()));
-// return result;
-// } else {
-//
-// Either<DataTypeDefinition, TitanOperationStatus> dataTypeByUid = this.getDataTypeByUid(oldDataTypeDefinition.getUniqueId());
-// if (dataTypeByUid.isRight()) {
-// TitanOperationStatus status = addPropertiesToDataType.right().value();
-// log.debug("Failed to get data type {} after update. Status is {}", oldDataTypeDefinition.getUniqueId(), status.name());
-// BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("UpdateDataType", "Property", status.name());
-// result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
-// } else {
-// result = Either.left(dataTypeByUid.left().value());
-// }
-// }
-//
-// return result;
-//
-// }
-// }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/Migration1702.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/Migration1702.java
deleted file mode 100644
index 6fa8b45734..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1702/Migration1702.java
+++ /dev/null
@@ -1,1406 +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.migration.v1702;
-
-import java.io.BufferedWriter;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.UUID;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.commons.math3.analysis.solvers.RiddersSolver;
-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.components.impl.ArtifactsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ImportUtils;
-import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
-import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
-import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
-import org.openecomp.sdc.be.config.Configuration.VfModuleProperty;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
-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.ArtifactDefinition;
-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.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.GroupProperty;
-import org.openecomp.sdc.be.model.GroupTypeDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.ResourceMetadataDefinition;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
-import org.openecomp.sdc.be.model.operations.impl.GroupOperation;
-import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
-import org.openecomp.sdc.be.resources.data.ArtifactData;
-import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
-import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
-import org.openecomp.sdc.be.resources.data.DataTypeData;
-import org.openecomp.sdc.be.resources.data.GroupData;
-import org.openecomp.sdc.be.resources.data.PropertyData;
-import org.openecomp.sdc.be.resources.data.PropertyValueData;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
-import org.openecomp.sdc.be.user.UserBusinessLogic;
-import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.util.ValidationUtils;
-import org.openecomp.sdc.exception.ResponseFormat;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.yaml.snakeyaml.Yaml;
-
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanGraphQuery;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-public class Migration1702 {
- private static final String CONFIG_GROUP_TYPES_YML = "/config/groupTypes.yml";
-
- private static final String CONFIG_DATA_TYPES_YML = "/config/dataTypes.yml";
-
- private static Logger log = LoggerFactory.getLogger(Migration1702.class.getName());
-
- @Autowired
- protected TitanGenericDao titanGenericDao;
- @Autowired
- protected ResourceOperation resourceOperation;
- @Autowired
- protected ServiceOperation serviceOperation;
- @Autowired
- private ServiceBusinessLogic serviceBusinessLogic;
- @Autowired
- private GroupTypeOperation groupTypeOperation;
- @Autowired
- private PropertyOperation propertyOperation;
- @Autowired
- private ComponentsUtils componentsUtils;
- @Autowired
- private GroupOperation groupOperation;
-
- @Autowired
- private ArtifactsBusinessLogic artifactsBusinessLogic;
-
- @Autowired
- private UserBusinessLogic userAdminManager;
-
- @Autowired
- private ComponentInstanceOperation componentInstanceOperation;
-
- public boolean migrate(String appConfigDir) {
- boolean result = true;
- String methodName = "alignCustomizationUUID";
-
- try {
- if (!alignCustomizationUUID()) {
- log.error("Failed to align customization UUID");
- result = false;
- return result;
- }
- methodName = "alignGroupDataType";
- if (!alignGroupDataType()) {
- log.error("Failed to align Group data type");
- result = false;
- return result;
- }
- methodName = "alignVfModuleProperties";
- if (!alignVfModuleProperties()) {
- log.error("Failed to align Vf Module Properties");
- result = false;
- return result;
- }
- methodName = "alignDataType";
- if (!alignDataType()) {
- log.error("Failed to align data type");
- result = false;
- return result;
- }
- methodName = "alignHeatEnv";
- if (!alignHeatEnv()) {
- log.error("Failed to align heat env on VF level");
- result = false;
- return result;
- }
- methodName = "alignModuleInstances";
- if (!alignModuleInstances()) {
- log.error("Failed to align module instances");
- result = false;
- return result;
- }
-
- } catch (Exception e) {
- log.error("Failed {} with exception: ", methodName, e);
- result = false;
- }
- return result;
- }
-
- private boolean alignModuleInstances() {
- log.info(" Align Module Instances");
- boolean result = true;
- boolean statusToReturn = true;
-
- Writer writer = null;
-
- try {
- long time = System.currentTimeMillis();
- writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("runstatusModules_" + time + ".csv"), "utf-8"));
-
- writer.write("resource id, instance id, group id, status\n");
-
- Either<List<ServiceMetadataData>, TitanOperationStatus> allServices = titanGenericDao.getByCriteria(NodeTypeEnum.Service, null, ServiceMetadataData.class);
- if (allServices.isRight()) {
- if (allServices.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.error("Align heat env on Vf - Failed to fetch services {}", allServices.right().value());
- result = false;
- statusToReturn = false;
- return statusToReturn;
- } else {
- log.debug("No Services. ");
- return statusToReturn;
- }
- }
- log.info("Need to handle {} services", allServices.left().value().size());
- long handledServices = 0;
- for (ServiceMetadataData metadata : allServices.left().value()) {
- String serviceId = metadata.getMetadataDataDefinition().getUniqueId();
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> riRes = componentInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource);
- if (riRes.isRight()) {
- if (riRes.right().value() == TitanOperationStatus.NOT_FOUND) {
- log.info("No instancces for service {}", serviceId);
- } else {
- log.info("Align vf modules - failed to fetch component instances for service {} error {}", riRes.right().value());
- writeModuleResultToFile(writer, serviceId, null, null, riRes.right().value());
- statusToReturn = false;
- }
- ++handledServices;
- continue;
- }
- List<ComponentInstance> componentInstances = riRes.left().value().left;
- for (ComponentInstance ci : componentInstances) {
- Either<TitanVertex, TitanOperationStatus> ciVertexRes = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), ci.getUniqueId());
- if (ciVertexRes.isRight()) {
- log.info("Failed to fetch vertex for component instance {}, error {}", ci.getUniqueId(), ciVertexRes.right().value());
- writeModuleResultToFile(writer, serviceId, ci.getUniqueId(), null, ciVertexRes.right().value());
- statusToReturn = false;
- continue;
- }
- TitanVertex ciVertex = ciVertexRes.left().value();
- if (createGroupInstancesOnComponentInstance(writer, ci, ciVertex, serviceId) == false) {
- statusToReturn = false;
- continue;
- }
- }
- writer.flush();
- ++handledServices;
- }
-
- log.info("Handled {} services", handledServices);
- } catch (Exception e) {
- log.error("Failed {} with exception: ", "alignModuleInstances", e);
- result = false;
- statusToReturn = false;
- } finally {
-
- log.info(" Align Module Instances finished");
- if (!result) {
- log.info("Doing rollback");
- titanGenericDao.rollback();
- } else {
- log.info("Doing commit");
- titanGenericDao.commit();
- }
- try {
- writer.flush();
- writer.close();
- } catch (Exception ex) {
- /* ignore */}
- }
- return statusToReturn;
- }
-
- private boolean createGroupInstancesOnComponentInstance(Writer writer, ComponentInstance ci, TitanVertex ciVertex, String serviceId) {
- boolean statusToReturn = true;
-
- Map<String, Object> properties = titanGenericDao.getProperties(ciVertex);
- ComponentInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.ResourceInstance.getName(), GraphElementTypeEnum.Node, properties, ComponentInstanceData.class);
-
- Either<List<GroupDefinition>, TitanOperationStatus> groupEither = groupOperation.getAllGroupsFromGraph(ci.getComponentUid(), NodeTypeEnum.Resource);
- if (groupEither.isRight()) {
- if (groupEither.right().value() != TitanOperationStatus.OK && groupEither.right().value() != TitanOperationStatus.NOT_FOUND) {
- TitanOperationStatus status = groupEither.right().value();
- log.error("Failed to associate group instances to component instance {}. Status is {}", ci.getUniqueId(), status);
- writeModuleResultToFile(writer, serviceId, ci.getUniqueId(), null, status);
- return false;
- } else {
- log.debug("No groups for component instance {}. ", ci.getUniqueId());
-
- writeModuleResultToFile(writer, serviceId, ci.getUniqueId(), null, "No groups");
- return true;
- }
- }
- List<GroupDefinition> groupsIמResource = groupEither.left().value();
- if (groupsIמResource != null && !groupsIמResource.isEmpty()) {
- List<GroupDefinition> vfGroupsListInResource = groupsIמResource.stream().filter(p -> p.getType().equals("org.openecomp.groups.VfModule")).collect(Collectors.toList());
-
- for (GroupDefinition groupInResource : vfGroupsListInResource) {
- Iterator<Edge> edgesToInstances = ciVertex.edges(Direction.OUT, GraphEdgeLabels.GROUP_INST.getProperty());
- boolean exist = false;
- String normalizedName = ValidationUtils.normalizeComponentInstanceName(ci.getNormalizedName() + ".." + groupInResource.getName());
- String grInstId = UniqueIdBuilder.buildResourceInstanceUniuqeId(ci.getUniqueId(), groupInResource.getUniqueId(), normalizedName);
-
-
- while (edgesToInstances.hasNext()) {
- Edge edgeToInst = edgesToInstances.next();
- Vertex grInstVertex = edgeToInst.inVertex();
- String grId = (String) titanGenericDao.getProperty((TitanVertex) grInstVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- if (grId.equals(grInstId)) {
- exist = true;
- break;
- }
- }
- if (!exist) {
- Either<GroupInstance, StorageOperationStatus> status = componentInstanceOperation.createGroupInstance(ciVertex, groupInResource, ci);
- if (status.isRight()) {
- log.error("Failed to create group instance {} in component instance {}. Status is {}", grInstId, ci.getUniqueId(), status.right().value());
- statusToReturn = false;
- writeModuleResultToFile(writer, serviceId, ci.getUniqueId(), grInstId, status.right().value());
- } else {
- writeModuleResultToFile(writer, serviceId, ci.getUniqueId(), grInstId, "OK");
- }
- } else {
- writeModuleResultToFile(writer, serviceId, ci.getUniqueId(), grInstId, "Exist");
- }
-
- }
- }
- return statusToReturn;
- }
-
- @SuppressWarnings("resource")
- private boolean alignHeatEnv() {
- Writer writer = null;
- log.info(" Align heat env on Vf level");
- boolean statusToReturn = true;
-
- boolean result = true;
- try {
- long time = System.currentTimeMillis();
- writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("runstatusEnv_" + time + ".csv"), "utf-8"));
-
- writer.write("resource id, operation, artifact id, status\n");
- User user = buildDummyUser();
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> allResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
- if (allResources.isRight()) {
- if (allResources.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.error("Align heat env on Vf - Failed to fetch resources {}", allResources.right().value());
- statusToReturn = false;
- result = false;
- return statusToReturn;
- } else {
- log.debug("No VF resources. ");
- return result;
- }
- }
- List<ResourceMetadataData> resources = allResources.left().value();
- log.debug("Need to handle {} resources", resources.size());
-
- long totalHandledArtifacts = 0;
- for (ResourceMetadataData metadata : resources) {
- Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> artifactNodesRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) metadata.getUniqueId(),
- GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class);
- if (artifactNodesRes.isRight()) {
- if (artifactNodesRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.error("Align heat env on Vf - Failed to fetch artifacts for resources {}", metadata.getUniqueId(), artifactNodesRes.right().value());
- writer.write(metadata.getUniqueId() + ",get artifacts, ,Failed to fetch artifacts " + artifactNodesRes.right().value() + "\n");
- statusToReturn = false;
- continue;
- } else {
- log.debug("No artifact for resource {} . ", metadata.getUniqueId());
- writer.write(metadata.getUniqueId() + ",get artifacts, ,No artfacts\n");
- continue;
- }
- }
- List<ImmutablePair<ArtifactData, GraphEdge>> artifacts = artifactNodesRes.left().value();
-
- for (ImmutablePair<ArtifactData, GraphEdge> pair : artifacts) {
- ArtifactData artifactData = pair.left;
- if (isNeedCreatePlaceHolder(artifactData)) {
- // check if exist heat env - if not -> create
- String heatEnvId = (String) artifactData.getUniqueId() + "env";
- if (validateOrCreateHeatEnv(user, metadata, artifactData, heatEnvId, writer) == false) {
- statusToReturn = false;
- }
- // check if connected to group - if not -> connect
- if (validateOrAssociateHeatAnv(metadata, artifactData, heatEnvId, writer) == false) {
- statusToReturn = false;
- }
- ++totalHandledArtifacts;
- writer.flush();
- }
-
- }
- }
- log.debug("Total handled {} artifacts", totalHandledArtifacts);
- } catch (Exception e) {
- log.error("Failed {} with exception: ", "alignHeatEnv", e);
- result = false;
- } finally {
-
- log.info("Aling heat env on VF level finished ");
- if (!result) {
- log.info("Doing rollback");
- titanGenericDao.rollback();
- } else {
- log.info("Doing commit");
- titanGenericDao.commit();
- }
- try {
- writer.flush();
- writer.close();
- } catch (Exception ex) {
- /* ignore */}
- }
- return statusToReturn;
- }
-
- private boolean validateOrAssociateHeatAnv(ResourceMetadataData metadata, ArtifactData artifactData, String heatEnvId, Writer writer) {
- boolean statusToReturn = true;
-
- String resourceId = (String) metadata.getUniqueId();
- Either<ArtifactData, TitanOperationStatus> heatEnvArtifactRes = titanGenericDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatEnvId, ArtifactData.class);
- if (heatEnvArtifactRes.isRight()) {
- log.error("Align heat env on Vf - Failed to fetch heat env node for id {} {}", heatEnvId, heatEnvArtifactRes.right().value());
- writeResultToFile(writer, "get artifact node for relation", resourceId, heatEnvId, heatEnvArtifactRes.right().value());
- return false;
- }
- ArtifactData heatEnvArtifact = heatEnvArtifactRes.left().value();
-
- Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> groupsForHeatRes = titanGenericDao.getParentNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) artifactData.getUniqueId(),
- GraphEdgeLabels.GROUP_ARTIFACT_REF, NodeTypeEnum.Group, GroupData.class);
- if (groupsForHeatRes.isRight()) {
- writeResultToFile(writer, "getChildrenNodes groups for heat", resourceId, (String) artifactData.getUniqueId(), groupsForHeatRes.right().value());
- if (groupsForHeatRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.error("Align heat env on Vf - Failed to fetch groups for heat artifact {} in resources {} : {}", artifactData.getUniqueId(), metadata.getUniqueId(), groupsForHeatRes.right().value());
- return false;
- } else {
- log.debug("Align heat env on Vf - No groups for heat artifact {} in resources {} : {}", artifactData.getUniqueId(), metadata.getUniqueId(), groupsForHeatRes.right().value());
- return true;
- }
- }
- List<ImmutablePair<GroupData, GraphEdge>> groupsForHeat = groupsForHeatRes.left().value();
- Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> groupsForHeatEnvRes = titanGenericDao.getParentNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatEnvId, GraphEdgeLabels.GROUP_ARTIFACT_REF, NodeTypeEnum.Group,
- GroupData.class);
- List<ImmutablePair<GroupData, GraphEdge>> groupsForHeatEnv;
- if (groupsForHeatEnvRes.isRight()) {
- if (groupsForHeatEnvRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.error("Align heat env on Vf - Failed to fetch groups for heat env artifact {} in resources {} : ", artifactData.getUniqueId(), metadata.getUniqueId(), groupsForHeatEnvRes.right().value());
- writeResultToFile(writer, "getChildrenNodes groups for heat env", resourceId, heatEnvId, groupsForHeatEnvRes.right().value());
- return false;
- } else {
- groupsForHeatEnv = new ArrayList<>();
- }
- } else {
- groupsForHeatEnv = groupsForHeatEnvRes.left().value();
- }
-
- for (ImmutablePair<GroupData, GraphEdge> heatGroup : groupsForHeat) {
- // check if exist
- boolean exist = false;
- GroupDataDefinition groupDataDefinition = heatGroup.left.getGroupDataDefinition();
- for (ImmutablePair<GroupData, GraphEdge> heatEnvGroup : groupsForHeatEnv) {
- if (groupDataDefinition.getName().equals(heatEnvGroup.left.getGroupDataDefinition().getName())) {
- exist = true;
- break;
- }
- }
- String groupId = (String) heatGroup.left.getUniqueId();
- if (!exist) {
- // need associate
-
- Map<String, Object> properties = new HashMap<String, Object>();
- properties.put(GraphPropertiesDictionary.NAME.getProperty(), heatEnvArtifact.getLabel());
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(heatGroup.left, heatEnvArtifact, GraphEdgeLabels.GROUP_ARTIFACT_REF, properties);
- log.trace("After associate group {} to artifact {}", groupDataDefinition.getName(), heatEnvArtifact.getUniqueIdKey());
- if (createRelation.isRight()) {
- log.error("Align heat env on Vf - Failed to associate heat env artifact {} to group {} : {}", artifactData.getUniqueId(), groupDataDefinition.getUniqueId(), createRelation.right().value());
-
- writeResultToFile(writer, "associate to group- relation" + groupId, resourceId, heatEnvId, groupsForHeatRes.right().value());
- statusToReturn = false;
- } else {
- writeResultToFile(writer, "associate to group " + groupId, resourceId, heatEnvId, "OK");
- }
- } else {
- writeResultToFile(writer, "associate group " + groupId, resourceId, heatEnvId, "Exist");
- }
- }
- return statusToReturn;
- }
-
- private boolean validateOrCreateHeatEnv(User user, ResourceMetadataData metadata, ArtifactData artifactData, String heatEnvId, Writer writer) {
- String resourceId = metadata.getMetadataDataDefinition().getUniqueId();
- boolean statusToReturn = true;
- Either<ArtifactData, TitanOperationStatus> node = titanGenericDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatEnvId, ArtifactData.class);
- boolean isContinue = true;
- if (node.isRight()) {
- if (TitanOperationStatus.NOT_FOUND == node.right().value()) {
- // create
- ArtifactDefinition heatArtifact = new ArtifactDefinition(artifactData.getArtifactDataDefinition());
- ResourceMetadataDefinition resourceMetadataDataDefinition = new ResourceMetadataDefinition((ResourceMetadataDataDefinition) metadata.getMetadataDataDefinition());
-
- Resource resource = new Resource(resourceMetadataDataDefinition);
-
- String heatUpdater = heatArtifact.getUserIdLastUpdater();
- Either<User, ActionStatus> userHeat = userAdminManager.getUser(heatUpdater, true);
-
- Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(heatArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, (String) metadata.getUniqueId(), NodeTypeEnum.Resource,
- metadata.getMetadataDataDefinition().getName(), userHeat.left().value(), resource, null, false);
- if (createHeatEnvPlaceHolder.isRight()) {
- log.error("Align heat env on Vf - Failed to create heat env {} for heat {} : {}", heatEnvId, heatArtifact.getUniqueId(), createHeatEnvPlaceHolder.right().value().getText());
- writeResultToFile(writer, "create placeholder", resourceId, heatEnvId, createHeatEnvPlaceHolder.right().value().getText());
- isContinue = false;
- statusToReturn = false;
- } else {
- writeResultToFile(writer, "create placeholder", resourceId, heatEnvId, "OK");
- }
- } else {
- log.error("Align heat env on Vf - Failed to fetch heat env node for id {} {}", heatEnvId, node.right().value());
- writeResultToFile(writer, "create placeholder - get", resourceId, heatEnvId, node.right().value());
- isContinue = false;
- statusToReturn = false;
- }
- } else {
- writeResultToFile(writer, "create placeholder - get", resourceId, heatEnvId, "Exist");
- }
- if (isContinue) {
- log.debug("associate heat env artifact to all resources ");
- String heatUniqueId = (String) artifactData.getUniqueId();
- Either<TitanVertex, TitanOperationStatus> heatVertexRes = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatUniqueId);
- if (heatVertexRes.isRight()) {
- log.debug("Failed to fetch vertex for heat {} error {}", heatUniqueId, heatVertexRes.right().value());
- writeResultToFile(writer, "create placeholder - get heat vertex", resourceId, heatEnvId, heatVertexRes.right().value());
- statusToReturn = false;
- return statusToReturn;
- }
- TitanVertex heatVertex = heatVertexRes.left().value();
- Either<TitanVertex, TitanOperationStatus> heatEnvVertexRes = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatEnvId);
- if (heatEnvVertexRes.isRight()) {
- log.debug("Failed to fetch vertex for heat env {} error {}", heatEnvId, heatEnvVertexRes.right().value());
- writeResultToFile(writer, "create placeholder - get heat env vertex", resourceId, heatEnvId, heatEnvVertexRes.right().value());
- statusToReturn = false;
- return statusToReturn;
- }
-
- Vertex heatEnvVertex = heatEnvVertexRes.left().value();
- Iterator<Edge> edgesToHeat = heatVertex.edges(Direction.IN, GraphEdgeLabels.ARTIFACT_REF.name());
- while (edgesToHeat.hasNext()) {
- Edge edgeToHeat = edgesToHeat.next();
- boolean exist = false;
- Vertex outVertexHeat = edgeToHeat.outVertex();
- Map<String, Object> outVertexProps = titanGenericDao.getProperties(outVertexHeat);
-
- String resIdToHeat = (String) outVertexProps.get(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
-
- Iterator<Edge> edgesToEnv = heatEnvVertex.edges(Direction.IN, GraphEdgeLabels.ARTIFACT_REF.name());
- while (edgesToEnv.hasNext()) {
- Edge edgeToEnv = edgesToEnv.next();
- Vertex outVertexEnv = edgeToEnv.outVertex();
- String resIdToEnv = (String) titanGenericDao.getProperty((TitanVertex) outVertexEnv, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- if (resIdToHeat.equals(resIdToEnv)) {
- exist = true;
- break;
- }
- }
- if (!exist) {
- Map<String, Object> properties = titanGenericDao.getProperties(edgeToHeat);
- // need to associate additional resource to heat env
- // update artifact label on edge
- String heatEnvLabel = (String) titanGenericDao.getProperty((TitanVertex) heatEnvVertex, GraphPropertiesDictionary.ARTIFACT_LABEL.getProperty());
- properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), heatEnvLabel);
-
- TitanOperationStatus createEdge = titanGenericDao.createEdge(outVertexHeat, heatEnvVertex, GraphEdgeLabels.ARTIFACT_REF, properties);
- if (createEdge == TitanOperationStatus.OK) {
- writeResultToFile(writer, "associate to resource " + resIdToHeat, resourceId, heatEnvId, "OK");
- } else {
- writeResultToFile(writer, "associate to resource " + resIdToHeat, resourceId, heatEnvId, createEdge);
- statusToReturn = false;
- }
- } else {
- writeResultToFile(writer, "associate to resource " + resIdToHeat, resourceId, heatEnvId, "Exist");
- }
- }
- }
- return statusToReturn;
- }
-
- private void writeResultToFile(Writer writer, String op, String resourceId, String artifactD, Object status) {
- try {
- StringBuffer sb = new StringBuffer(resourceId);
- sb.append(",").append(op).append(",").append(artifactD).append(",").append(status).append("\n");
- writer.write(sb.toString());
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- private void writeModuleResultToFile(Writer writer, String resourceId, String instanceId, String groupId, Object status) {
- try {
- StringBuffer sb = new StringBuffer(resourceId);
- sb.append(",").append(instanceId).append(",").append(groupId).append(",").append(status).append("\n");
- writer.write(sb.toString());
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- private boolean isNeedCreatePlaceHolder(ArtifactData artifactData) {
- String artifactType = artifactData.getArtifactDataDefinition().getArtifactType();
- ArtifactTypeEnum type = ArtifactTypeEnum.findType(artifactType);
- if (ArtifactGroupTypeEnum.DEPLOYMENT == artifactData.getArtifactDataDefinition().getArtifactGroupType() && (ArtifactTypeEnum.HEAT == type || ArtifactTypeEnum.HEAT_NET == type || ArtifactTypeEnum.HEAT_VOL == type)) {
- return true;
- }
- return false;
- }
-
- private boolean alignVfModuleProperties() {
- boolean result = true;
- try {
- log.info(" Align Vf module properties");
-
- final Pattern pattern = Pattern.compile("\\..(.*?)\\..");
- final String LABEL_NAME = "vf_module_label";
- final String VOLUME_GROUP_NAME = "volume_group";
-
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- if (graph.isRight()) {
- log.error("Align Vf module properties - Failed to get graph {}", graph.right().value());
- result = false;
- return result;
- }
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> allResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
-
- if (allResources.isRight()) {
- if (allResources.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("Align Vf module properties - no VF resources");
- result = true;
- return result;
- } else {
- log.error("Align Vf module properties - generateTosca failed fetch all resources,error {}", allResources.right().value());
- result = false;
- return result;
- }
- }
-
- List<ResourceMetadataData> listAllVFs = allResources.left().value();
-
- ComponentParametersView componentParametersView = new ComponentParametersView(true);
- componentParametersView.setIgnoreGroups(false);
- componentParametersView.setIgnoreArtifacts(false);
-
- log.info("Align Vf module properties - Starting to update the VF's");
- Map<String, VfModuleProperty> vfModuleProperties = ConfigurationManager.getConfigurationManager().getConfiguration().getVfModuleProperties();
- for (ResourceMetadataData resourceMetadataData : listAllVFs) {
- String uniqueId = (String) resourceMetadataData.getUniqueId();
-
- Either<Resource, StorageOperationStatus> resourceResponse = resourceOperation.getResource(uniqueId, componentParametersView, true);
-
- if (resourceResponse.isRight()) {
- log.error("Align Vf module properties - failed resource with UniqueID: {} , error {}", uniqueId, resourceResponse.right().value());
- result = false;
- return result;
- }
-
- Resource resource = resourceResponse.left().value();
- List<GroupDefinition> groups = resource.getGroups();
-
- if (groups == null || groups.isEmpty()) {
- log.debug("Align Vf module properties - resource UniqueID: {} does not contain groups", resource.getUniqueId());
- continue;
- } else {
-
- for (GroupDefinition groupDefinition : groups) {
-
- if (groupDefinition.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
- log.info("update vf module proerties for group {} ", groupDefinition.getUniqueId());
-
- List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
- if (properties == null) {
- properties = new ArrayList<>();
- }
- Boolean isBase = false;
- List<String> artifacts = groupDefinition.getArtifacts();
- if (artifacts == null) {
- artifacts = new ArrayList<>();
- }
- Boolean isVolumeGroup = false;
- for (String artifactId : artifacts) {
- ArtifactDefinition artifactDef = null;
- Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts();
- artifactDef = findArtifactInList(deploymentArtifacts, artifactId);
- if (artifactDef != null && artifactDef.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
- isVolumeGroup = true;
- break;
- }
- }
- for (GroupProperty groupProperty : properties) {
- if (groupProperty.getName().equals(Constants.IS_BASE)) {
- isBase = Boolean.valueOf(groupProperty.getValue());
- break;
- }
- }
-
- if (null == isBase) {
- log.error("Align Vf module properties - isBase not found in DEFAULT_GROUP_VF_MODULE");
- result = false;
- return result;
- }
-
- String vfModuleLabel = null;
- String moduleName = groupDefinition.getName();
- Matcher matcher = pattern.matcher(moduleName);
-
- if (matcher.find()) {
- vfModuleLabel = matcher.group(1);
- } else {
- vfModuleLabel = moduleName;
- }
-
- boolean isBasePrimitive = isBase;
- boolean isVolumeGroupPrimitive = isVolumeGroup;
- String vfModuleLabelFinal = vfModuleLabel;
- List<GroupProperty> propertiesToAdd = new ArrayList<>();
- properties.stream().forEach(p -> {
- if (p.getValueUniqueUid() == null) {
- if (vfModuleProperties.containsKey(p.getName())) {
- if (isBasePrimitive) {
- p.setValue(vfModuleProperties.get(p.getName()).getForBaseModule());
- } else {
- p.setValue(vfModuleProperties.get(p.getName()).getForNonBaseModule());
- }
- } else if (p.getName().equals(VOLUME_GROUP_NAME)) {
- p.setValue(String.valueOf(isVolumeGroupPrimitive));
- } else if (p.getName().equals(LABEL_NAME)) {
- p.setValue(vfModuleLabelFinal);
- }
- propertiesToAdd.add(p);
- }
-
- });
-
- List<GroupProperty> propertiesAlreadyExistOnGraph = properties.stream().filter(p -> !(p.getValueUniqueUid() == null || p.getValueUniqueUid().isEmpty())).collect(Collectors.toList());
- int numOfPropertiesAlreadyExist = propertiesAlreadyExistOnGraph.size();
-
- log.debug("Need to update default values vfModule {} properties {} ", properties.size(), properties);
-
- Either<GroupTypeDefinition, TitanOperationStatus> groupTypeRes = groupTypeOperation.getGroupTypeByUid(groupDefinition.getTypeUid());
- if (groupTypeRes.isRight()) {
- TitanOperationStatus operationStatus = groupTypeRes.right().value();
- log.debug("Failed to find group type {}",groupDefinition.getTypeUid());
- if (operationStatus == TitanOperationStatus.NOT_FOUND) {
- result = false;
- return result;
- }
- }
-
- GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
- List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
- Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
-
- int i = numOfPropertiesAlreadyExist + 1;
- for (GroupProperty prop : propertiesToAdd) {
- if (prop.getUniqueId() == null || prop.getUniqueId().isEmpty()) {
- continue;
- }
- GroupData groupData = new GroupData(groupDefinition);
-
- Either<PropertyValueData, TitanOperationStatus> addPropertyToGroup = groupOperation.addPropertyToGroup(groupData, prop, groupTypePropertiesMap.get(prop.getName()), i);
- if (addPropertyToGroup.isRight()) {
- log.info("Failed to add properties {} to group type :{} error {} ", prop.getName(), groupData.getUniqueId(), addPropertyToGroup.right().value());
- result = false;
- return result;
- }
- ++i;
- }
- }
- }
- }
- }
- } catch (Exception e) {
- log.error("Failed {} with exception: ", "alignVfModuleProperties", e);
- result = false;
- } finally {
- log.info(" Align Vf module properties finished");
- if (!result) {
- log.info("Doing rollback");
- titanGenericDao.rollback();
- } else {
- log.info("Doing commit");
- titanGenericDao.commit();
- }
- }
- return true;
- }
-
- private ArtifactDefinition findArtifactInList(Map<String, ArtifactDefinition> deploymentArtifacts, String artifactId) {
- Optional<ArtifactDefinition> op = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(artifactId)).findAny();
- if (op.isPresent())
- return op.get();
- return null;
- }
-
- private boolean generateTosca() {
- log.info("Regenerate Tosca and CSAR for VFs and Services");
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- if (graph.isRight()) {
- log.error("Failed to get graph {}", graph.right().value());
- return false;
- }
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
-
- User user = buildDummyUser();
-
- Map<String, Object> propsHasNot = new HashMap<String, Object>();
- propsHasNot.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- propsHasNot.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> allResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, propsHasNot, ResourceMetadataData.class);
- if (allResources.isRight()) {
- if (allResources.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("generateTosca - no VF resources");
- } else {
- log.info("generateTosca failed fetch all resources,error {}", allResources.right().value());
- return false;
- }
- } else {
- if (!handleComponents(user, allResources.left().value(), resourceOperation)) {
- log.info("generateTosca failed generate tosca artifacts for resources");
- return false;
-
- }
- }
- Either<List<ServiceMetadataData>, TitanOperationStatus> allServices = titanGenericDao.getByCriteria(NodeTypeEnum.Service, null, propsHasNot, ServiceMetadataData.class);
- if (allServices.isRight()) {
- if (allServices.right().value() == TitanOperationStatus.NOT_FOUND) {
- log.debug("generateTosca - no services");
-
- } else {
- log.debug("generateTosca failed fetch all services,error {}",allServices.right().value());
- return false;
- }
- } else {
- if (!handleComponents(user, allServices.left().value(), serviceOperation)) {
- log.info("generateTosca failed generate tosca artifacts for services");
- return false;
-
- }
- }
- log.info("Regenerate Tosca and CSAR for VFs and Services finished");
- return true;
- }
-
- private <T extends ComponentMetadataData> boolean handleComponents(User user, List<T> allResources, ComponentOperation operation) {
- for (ComponentMetadataData resource : allResources) {
- if (resource.getMetadataDataDefinition().isDeleted() == null || !resource.getMetadataDataDefinition().isDeleted()) {
- Either<Component, StorageOperationStatus> component = operation.getComponent((String) resource.getUniqueId(), true);
- if (component.isRight()) {
- log.info("generateTosca failed fetch component with id {} , error {}", (String) resource.getUniqueId(), component.right().value());
- return false;
- }
- if (populateToscaArtifactsWithLog(component.left().value(), user) != ActionStatus.OK) {
- return false;
- }
- }
- }
- return true;
- }
-
- private boolean alignCustomizationUUID() {
- boolean result = true;
- try {
- log.info("Update customization UUID for all component instances on graph");
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- if (graph.isRight()) {
- log.error("Failed to get graph {}", graph.right().value());
- return result;
- }
- TitanGraph tGraph = graph.left().value();
- TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query();
- query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ResourceInstance.getName());
- Iterable<TitanVertex> vertices = query.vertices();
- if (vertices == null) {
- log.info("No component instances on graph");
- return result;
- }
- Iterator<TitanVertex> iterator = vertices.iterator();
- if (!iterator.hasNext()) {
- log.info("No component instances on graph");
- }
- while (iterator.hasNext()) {
- TitanVertex vertex = iterator.next();
- String property = (String) titanGenericDao.getProperty(vertex, GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty());
- if (!ValidationUtils.validateStringNotEmpty(property)) {
- UUID uuid = UUID.randomUUID();
- vertex.property(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty(), uuid.toString());
- }
- }
- } catch (Exception e) {
- log.error("Failed {} with exception: ", "alignCustomizationUUID", e);
- result = false;
- } finally {
- log.info("Update customization UUID finished ");
- if (!result) {
- log.info("Doing rollback");
- titanGenericDao.rollback();
- } else {
- log.info("Doing commit");
- titanGenericDao.commit();
- }
- }
- return result;
- }
-
- private ActionStatus populateToscaArtifactsWithLog(Component component, User user) {
- ActionStatus ret = ActionStatus.OK;
- LifecycleStateEnum lifecycleState = component.getLifecycleState();
- if (!needRegenarateTosca(lifecycleState)) {
- log.debug("Component {} is in state {}, don't generatate Tosca", component.getUniqueId(), lifecycleState);
- return ret;
- }
-
- try {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> populateToscaArtifacts = serviceBusinessLogic.populateToscaArtifacts(component, user, true, false, true, true);
- if (populateToscaArtifacts.isLeft()) {
- log.debug("Added payload to tosca artifacts of component {} of type:{} with uniqueId:{}", component.getName(), component.getComponentType().getValue(), component.getUniqueId());
- } else {
- log.error("Failed to generate TOSCA artifacts for component {} of type:{} with uniqueId:{}", component.getName(), component.getComponentType().name(), component.getUniqueId());
- return ActionStatus.GENERAL_ERROR;
- }
- return ret;
- } catch (Exception e) {
- log.error("Exception Occured When filling tosca artifact payload for component {} of type:{} with uniqueId:{}", component.getName(), component.getComponentType().name(), component.getUniqueId(), e);
- return ActionStatus.GENERAL_ERROR;
- }
- }
-
- private boolean needRegenarateTosca(LifecycleStateEnum lifecycleState) {
- if (lifecycleState == LifecycleStateEnum.READY_FOR_CERTIFICATION || lifecycleState == LifecycleStateEnum.CERTIFICATION_IN_PROGRESS || lifecycleState == LifecycleStateEnum.CERTIFIED) {
- return true;
- }
- return false;
- }
-
- private User buildDummyUser() {
- User user = new User();
- user.setUserId("migrationTask");
- return user;
- }
-
- private boolean alignGroupDataType() {
- boolean result = true;
- try {
- log.info(" Align group data type properties");
- String categoryMigrationFile = CONFIG_GROUP_TYPES_YML;
- String yamlAsString;
- try {
-
- InputStream inputStream = getClass().getResourceAsStream(categoryMigrationFile);
- if (inputStream == null) {
- log.info("Failed to load input file : {}", categoryMigrationFile);
- result = false;
- return result;
- }
- yamlAsString = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
-
- } catch (Exception e) {
- log.info("Failed to load group types file exception : ", e);
- result = false;
- return result;
- }
-
- log.debug("received yaml: {}", yamlAsString);
-
- Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(yamlAsString);
-
- if (toscaJson == null || toscaJson.isEmpty()) {
- log.info("group types file is empty");
- result = false;
- return result;
- }
-
- Map<String, Object> vfModule = (Map<String, Object>) toscaJson.get("org.openecomp.groups.VfModule");
- if (vfModule == null || vfModule.isEmpty()) {
- log.info("No vfModule in group types file");
- result = false;
- return result;
- }
- Map<String, Object> properties = (Map<String, Object>) vfModule.get("properties");
- if (properties == null || properties.isEmpty()) {
- log.info("No properties for vfModule in group types file");
- result = false;
- return result;
- }
- Either<GroupTypeDefinition, StorageOperationStatus> latestGroupTypeByType = groupTypeOperation.getLatestGroupTypeByType("org.openecomp.groups.VfModule", true);
- if (latestGroupTypeByType.isRight()) {
- log.info("Failed to fetch org.openecomp.groups.VfModule group type, error :{}", latestGroupTypeByType.right().value());
- result = false;
- return result;
- }
- GroupTypeDefinition groupTypeInGraph = latestGroupTypeByType.left().value();
- List<PropertyDefinition> propertiesInGraph = groupTypeInGraph.getProperties();
-
- List<PropertyDefinition> propertiesToAdd = new ArrayList<>();
-
- properties.entrySet().stream().filter(e -> !ifExistOnGraph(e.getKey(), propertiesInGraph)).forEach(fe -> {
- PropertyDefinition property = new PropertyDefinition();
- property.setName(fe.getKey());
- Map<String, Object> definitionInYaml = (Map<String, Object>) fe.getValue();
- property.setType((String) definitionInYaml.get("type"));
- property.setRequired((Boolean) definitionInYaml.get("required"));
- property.setDescription((String) definitionInYaml.get("description"));
- String defaultValue = definitionInYaml.get("default") == null ? null : definitionInYaml.get("default").toString();
- if (defaultValue != null) {
- property.setDefaultValue(defaultValue);
- }
- propertiesToAdd.add(property);
- });
-
- if (!propertiesToAdd.isEmpty()) {
- log.debug("Need to add to vfModule {} properties {} ", propertiesToAdd.size(), propertiesToAdd);
-
- Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(groupTypeInGraph.getUniqueId(), NodeTypeEnum.GroupType, propertiesToAdd);
- if (addPropertiesToCapablityType.isRight()) {
- log.info("Failed to add properties to group type :{}", addPropertiesToCapablityType.right().value());
- result = false;
- return result;
- }
- } else {
- log.debug("No properties to add to vfModule");
- }
-
- } catch (Exception e) {
- log.error("Failed {} with exception: ", "alignGroupDataType", e);
- result = false;
- } finally {
- log.info(" Align group data type properties finished");
- if (!result) {
- log.info("Doing rollback");
- titanGenericDao.rollback();
- } else {
- log.info("Doing commit");
- titanGenericDao.commit();
- }
- }
- return result;
- }
-
- private boolean ifExistOnGraph(String name, List<PropertyDefinition> propertiesInGraph) {
- for (PropertyDefinition pd : propertiesInGraph) {
- if (pd.getName().equals(name)) {
- return true;
- }
- }
- return false;
- }
-
- public boolean alignDataType() {
-
- log.info(" Align data type properties");
-
- boolean isSuccessful = true;
- List<DataTypeDefinition> dataTypes = extractDataTypesFromYaml();
-
- if (CollectionUtils.isEmpty(dataTypes)) {
- isSuccessful = false;
- }
-
- List<ImmutablePair<DataTypeDefinition, Boolean>> createdElementTypes = new ArrayList<>();
-
- Iterator<DataTypeDefinition> elementTypeItr = dataTypes.iterator();
- if (isSuccessful) {
- try {
- while (elementTypeItr.hasNext()) {
- DataTypeDefinition elementType = elementTypeItr.next();
- String elementName = elementType.getName();
- Either<ActionStatus, ResponseFormat> validateElementType = validateDataType(elementType);
- if (validateElementType.isRight()) {
- log.debug("Failed to validate data type {}. Status is {}. ", elementName, validateElementType.right().value());
- isSuccessful = false;
- break;
- }
- log.debug("Going to get data type by name {}. ", elementName);
- Either<DataTypeDefinition, StorageOperationStatus> findElementType = propertyOperation.getDataTypeByNameWithoutDerived(elementName);
- if (findElementType.isRight()) {
- StorageOperationStatus status = findElementType.right().value();
- if (status != StorageOperationStatus.NOT_FOUND) {
- log.debug("Failed to fetch data type {}. Status is {}. ", elementName, validateElementType.right().value());
- isSuccessful = false;
- break;
- } else {
- log.debug("Going to add data type with name {}. ", elementName);
- Either<DataTypeDefinition, StorageOperationStatus> dataModelResponse = propertyOperation.addDataType(elementType);
-
- if (dataModelResponse.isRight()) {
- if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
- log.debug("Failed to add data type {}. Status is {}. ", elementName, dataModelResponse.right().value());
- isSuccessful = false;
- break;
- } else {
- createdElementTypes.add(new ImmutablePair<DataTypeDefinition, Boolean>(elementType, false));
- }
- } else {
- createdElementTypes.add(new ImmutablePair<DataTypeDefinition, Boolean>(dataModelResponse.left().value(), true));
- }
-
- }
- } else {
- DataTypeDefinition dataTypeDefinition = findElementType.left().value();
- log.debug("Going to update data type with name {}. ", elementName);
- Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteDataTypeRes = propertyOperation.deleteAllPropertiesAssociatedToNode(NodeTypeEnum.DataType, dataTypeDefinition.getUniqueId());
- if (deleteDataTypeRes.isRight()) {
- StorageOperationStatus status = deleteDataTypeRes.right().value();
- if (status != StorageOperationStatus.OK) {
-
- log.debug("Failed to update data type {}. Status is {}. ", elementName, deleteDataTypeRes.right().value());
- isSuccessful = false;
- break;
- }
- }
-
- Either<Map<String, PropertyData>, TitanOperationStatus> updateDataTypeRes = propertyOperation.addPropertiesToElementType(dataTypeDefinition.getUniqueId(), NodeTypeEnum.DataType, elementType.getProperties());
-
- if (updateDataTypeRes.isRight()) {
- TitanOperationStatus status = updateDataTypeRes.right().value();
-
- log.debug("Failed to update data type {}. Status is {}. ", elementName, updateDataTypeRes.right().value());
- isSuccessful = false;
- break;
-
- } else {
- createdElementTypes.add(new ImmutablePair<DataTypeDefinition, Boolean>(elementType, true));
- }
-
- DataTypeData dataTypeData = new DataTypeData();
- dataTypeData.setDataTypeDataDefinition(elementType);
- dataTypeData.getDataTypeDataDefinition().setUniqueId(dataTypeDefinition.getUniqueId());
- long modificationTime = System.currentTimeMillis();
- dataTypeData.getDataTypeDataDefinition().setModificationTime(modificationTime);
-
- Either<DataTypeData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(dataTypeData, DataTypeData.class);
- if (updateNode.isRight()) {
- TitanOperationStatus operationStatus = updateNode.right().value();
- log.debug("Failed to update modification time data type {} from graph. status is {}",
- dataTypeDefinition.getUniqueId() ,operationStatus);
- BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToDataType", "Failed to fetch data type. Status is " + operationStatus, ErrorSeverity.ERROR);
- isSuccessful = false;
- break;
- } else {
- log.debug("Update data type uid {}. Set modification time to {}", dataTypeDefinition.getUniqueId(), modificationTime);
- isSuccessful = true;
- }
- }
- }
- } finally {
- log.info(" Finish to align data type properties");
- if (isSuccessful) {
- propertyOperation.getTitanGenericDao().commit();
- } else {
- propertyOperation.getTitanGenericDao().rollback();
- }
- }
- }
- return isSuccessful;
- }
-
- @SuppressWarnings("unchecked")
- private List<DataTypeDefinition> extractDataTypesFromYaml() {
- String dataTypeYmlFilePath = CONFIG_DATA_TYPES_YML;
- String yamlAsString;
- try {
-
- InputStream inputStream = getClass().getResourceAsStream(dataTypeYmlFilePath);
- if (inputStream == null) {
- log.info("Failed to load input file : {}", dataTypeYmlFilePath);
- return null;
- }
- yamlAsString = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
-
- } catch (Exception e) {
- log.info("Failed to load group types file exception : ", e);
- return null;
- }
-
- log.debug("received yaml: {}", yamlAsString);
-
- String dataTypeName;
- List<DataTypeDefinition> dataTypes = new ArrayList<>();
-
- Map<String, Object> toscaJson = (Map<String, Object>) new Yaml().load(yamlAsString);
- Iterator<Entry<String, Object>> elementTypesEntryItr = toscaJson.entrySet().iterator();
- while (elementTypesEntryItr.hasNext()) {
- Entry<String, Object> elementTypeNameDataEntry = elementTypesEntryItr.next();
- dataTypeName = elementTypeNameDataEntry.getKey();
- Map<String, Object> elementTypeJsonData = (Map<String, Object>) elementTypeNameDataEntry.getValue();
-
- DataTypeDefinition dataType = new DataTypeDefinition();
- dataType.setName(dataTypeName);
-
- if (elementTypeJsonData != null) {
-
- if (elementTypeJsonData.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
- dataType.setDescription((String) elementTypeJsonData.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
- }
- if (elementTypeJsonData.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) {
- dataType.setDerivedFromName((String) elementTypeJsonData.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
- }
- List<PropertyDefinition> properties = getProperties(elementTypeJsonData);
- if (elementTypeJsonData.containsKey(ToscaTagNamesEnum.PROPERTIES.getElementName())) {
- dataType.setProperties(properties);
- }
- }
- dataTypes.add(dataType);
- }
-
- return dataTypes;
- }
-
- private List<PropertyDefinition> getProperties(Map<String, Object> toscaJson) {
- List<PropertyDefinition> values = null;
- Either<Map<String, PropertyDefinition>, ResultStatusEnum> properties = ImportUtils.getProperties(toscaJson);
-
- if (properties.isLeft()) {
- values = new ArrayList<>();
- Map<String, PropertyDefinition> propertiesMap = properties.left().value();
- if (propertiesMap != null && propertiesMap.isEmpty() == false) {
-
- for (Entry<String, PropertyDefinition> entry : propertiesMap.entrySet()) {
- String propName = entry.getKey();
- PropertyDefinition propertyDefinition = entry.getValue();
- PropertyDefinition newPropertyDefinition = new PropertyDefinition(propertyDefinition);
- newPropertyDefinition.setName(propName);
- values.add(newPropertyDefinition);
- }
- }
- }
-
- return values;
- }
-
- private Either<ActionStatus, ResponseFormat> validateDataType(DataTypeDefinition dataType) {
-
- String dataTypeName = dataType.getName();
- List<PropertyDefinition> properties = dataType.getProperties();
- if (properties == null) {
- // At least one parameter should be defined either in the properties
- // section or at one of the parents
- String derivedDataType = dataType.getDerivedFromName();
- // If there are no properties, then we can create a data type if it
- // is an abstract one or it derives from non abstract data type
- if ((derivedDataType == null || derivedDataType.isEmpty())) {
- if (false == isAbstract(dataType.getName())) {
- if (false == ToscaPropertyType.isScalarType(dataTypeName)) {
- log.debug("Data type {} must have properties unless it derives from non abstract data type",dataType.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
-
- return Either.right(responseFormat);
- }
- }
- } else {
- // if it is not a scalar data type and it derives from abstract
- // data type, we should reject the request.
- if (false == ToscaPropertyType.isScalarType(dataTypeName) && true == isAbstract(derivedDataType)) {
- log.debug("Data type {} which derived from abstract data type must have at least one property",dataType.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM, dataType, null);
-
- return Either.right(responseFormat);
- }
- }
- } else {
- // properties tag cannot be empty
- if (properties.isEmpty()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY, dataType, null);
-
- return Either.right(responseFormat);
- }
-
- // check no duplicates
- Set<String> collect = properties.stream().map(p -> p.getName()).collect(Collectors.toSet());
- if (collect != null) {
- if (properties.size() != collect.size()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DUPLICATE_PROPERTY, dataType, null);
-
- return Either.right(responseFormat);
- }
- }
-
- List<String> propertiesWithSameTypeAsDataType = properties.stream().filter(p -> p.getType().equals(dataType.getName())).map(p -> p.getName()).collect(Collectors.toList());
- if (propertiesWithSameTypeAsDataType != null && propertiesWithSameTypeAsDataType.isEmpty() == false) {
- log.debug("The data type contains properties with the type {}",dataType.getName(),dataType.getName());
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE, dataType, propertiesWithSameTypeAsDataType);
-
- return Either.right(responseFormat);
- }
- }
-
- String derivedDataType = dataType.getDerivedFromName();
- if (derivedDataType != null) {
- Either<DataTypeDefinition, StorageOperationStatus> derivedDataTypeByName = propertyOperation.getDataTypeByName(derivedDataType, true);
- if (derivedDataTypeByName.isRight()) {
- StorageOperationStatus status = derivedDataTypeByName.right().value();
- if (status == StorageOperationStatus.NOT_FOUND) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_DERIVED_IS_MISSING, dataType, null);
-
- return Either.right(responseFormat);
- } else {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.GENERAL_ERROR, dataType, null);
-
- return Either.right(responseFormat);
-
- }
- } else {
-
- DataTypeDefinition derivedDataTypeDef = derivedDataTypeByName.left().value();
- if (properties != null && properties.isEmpty() == false) {
-
- if (true == isScalarType(derivedDataTypeDef)) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_CANNOT_HAVE_PROPERTIES, dataType, null);
-
- return Either.right(responseFormat);
- }
-
- Set<String> allParentsProps = new HashSet<>();
- do {
- List<PropertyDefinition> currentParentsProps = derivedDataTypeDef.getProperties();
- if (currentParentsProps != null) {
- for (PropertyDefinition propertyDefinition : currentParentsProps) {
- allParentsProps.add(propertyDefinition.getName());
- }
- }
- derivedDataTypeDef = derivedDataTypeDef.getDerivedFrom();
- } while (derivedDataTypeDef != null);
-
- // Check that no property is already defined in one of the
- // ancestors
- Set<String> alreadyExistPropsCollection = properties.stream().filter(p -> allParentsProps.contains(p.getName())).map(p -> p.getName()).collect(Collectors.toSet());
- if (alreadyExistPropsCollection != null && alreadyExistPropsCollection.isEmpty() == false) {
- List<String> duplicateProps = new ArrayList<>();
- duplicateProps.addAll(alreadyExistPropsCollection);
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByDataType(ActionStatus.DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR, dataType, duplicateProps);
-
- return Either.right(responseFormat);
- }
-
- }
- }
- }
- return Either.left(ActionStatus.OK);
- }
-
- private boolean isAbstract(String dataTypeName) {
-
- ToscaPropertyType isPrimitiveToscaType = ToscaPropertyType.isValidType(dataTypeName);
-
- return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == true;
-
- }
-
- private boolean isScalarType(DataTypeDefinition dataTypeDef) {
-
- boolean isScalar = false;
- DataTypeDefinition dataType = dataTypeDef;
-
- while (dataType != null) {
-
- String name = dataType.getName();
- if (ToscaPropertyType.isScalarType(name)) {
- isScalar = true;
- break;
- }
-
- dataType = dataType.getDerivedFrom();
- }
-
- return isScalar;
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/DistributionStatusUpdate.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/DistributionStatusUpdate.java
deleted file mode 100644
index 744965ff68..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/DistributionStatusUpdate.java
+++ /dev/null
@@ -1,160 +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.migration.v1707;
-
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
-import org.apache.commons.collections.MapUtils;
-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.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
-import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-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.Service;
-import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import fj.data.Either;
-
-@Component("distributionStatusUpdate")
-public class DistributionStatusUpdate {
- private static Logger LOGGER = LoggerFactory.getLogger(DistributionStatusUpdate.class);
-
- @Autowired
- private ToscaOperationFacade toscaOperationFacade;
- @Autowired
- private TitanDao titanDao;
-
-
- public boolean migrate() {
- boolean result = true;
- Either<Map<GraphVertex, org.openecomp.sdc.be.model.Service>, StorageOperationStatus> getAllServiceComponentsRes = getAllServiceComponents();
- if(getAllServiceComponentsRes.isRight()){
- result = false;
- }
- if(result && MapUtils.isNotEmpty(getAllServiceComponentsRes.left().value())){
- updateDistributionStatusFromMetadata(getAllServiceComponentsRes.left().value());
- updateDistributionStatusToNotDistributed(getAllServiceComponentsRes.left().value());
- }
-
- toscaOperationFacade.commit();
-
- return result;
- }
-
-
- private void updateDistributionStatusToNotDistributed(Map<GraphVertex, org.openecomp.sdc.be.model.Service> components) {
-
- Map<GraphVertex, org.openecomp.sdc.be.model.Service> filteredComponents = components.entrySet()
- .stream()
- .filter(e -> e.getValue().getLifecycleState() != LifecycleStateEnum.CERTIFIED)
- .collect(Collectors.toMap(e -> e.getKey(), e -> (Service)e.getValue()));
-
- Service service;
- Either<GraphVertex, TitanOperationStatus> updateResponse;
- GraphVertex metadataV;
-
- for(Entry<GraphVertex, Service> currComponent : filteredComponents.entrySet()){
- metadataV = currComponent.getKey();
- service = currComponent.getValue();
- try {
- metadataV.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
- updateResponse = titanDao.updateVertex(metadataV);
-
- if (updateResponse.isRight()) {
- LOGGER.debug("failed to updateDistributionStatusToNotDistributed service {} error {}", service.getUniqueId(), updateResponse.right().value());
- }
-
- } catch (Exception e) {
- LOGGER.debug("failed to updateDistributionStatusToNotDistributed service {} error {}", service.getUniqueId(), e.toString());
- }
- }
- }
-
- private void updateDistributionStatusFromMetadata(Map<GraphVertex, org.openecomp.sdc.be.model.Service> components) {
- Service service;
- String statusFromMetadata;
- Either<GraphVertex, TitanOperationStatus> updateResponse;
- GraphVertex metadataV;
-
- for(Entry<GraphVertex, Service> currComponent : components.entrySet()){
- metadataV = currComponent.getKey();
- service = currComponent.getValue();
- try {
- statusFromMetadata = (String) metadataV.getJsonMetadataField(JsonPresentationFields.DISTRIBUTION_STATUS);
- metadataV.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, statusFromMetadata);
- updateResponse = titanDao.updateVertex(metadataV);
-
- if (updateResponse.isRight()) {
- LOGGER.debug("failed to updateDistributionStatusFromMetadata service {} error {}", service.getUniqueId(), updateResponse.right().value());
- }
-
- } catch (Exception e) {
- LOGGER.debug("failed to read distribution status of service {} error {}", service.getUniqueId(), e.toString());
- }
-
- }
- }
-
-
- public Either<Map<GraphVertex, org.openecomp.sdc.be.model.Service>, StorageOperationStatus> getAllServiceComponents() {
-
- Map<GraphVertex, org.openecomp.sdc.be.model.Service> components = new HashMap<>();
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> propertiesNotMatch = new EnumMap<>(GraphPropertyEnum.class);
- propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
- propertiesNotMatch.put(GraphPropertyEnum.IS_DELETED, true);
- Either<List<GraphVertex>, TitanOperationStatus> getVerticiesRes = toscaOperationFacade.getTitanDao().getByCriteria(null, propertiesToMatch, propertiesNotMatch, JsonParseFlagEnum.ParseAll);
-
- if (getVerticiesRes.isRight() && getVerticiesRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- LOGGER.debug("Failed to fetch all service components. Status is {}", getVerticiesRes.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticiesRes.right().value()));
- }
- if(getVerticiesRes.isLeft()){
- List<GraphVertex> componentVerticies = getVerticiesRes.left().value();
- for (GraphVertex componentV : componentVerticies) {
- ComponentParametersView filters = new ComponentParametersView(true);
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentsRes = toscaOperationFacade.getToscaElement(componentV.getUniqueId(), filters);
- if (getComponentsRes.isRight()) {
- return Either.right(getComponentsRes.right().value());
- }
- components.put(componentV, (Service) getComponentsRes.left().value());
- }
- }
- return Either.left(components);
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707.java
deleted file mode 100644
index 1012ebddd4..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707.java
+++ /dev/null
@@ -1,58 +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.migration.v1707;
-
-import org.openecomp.sdc.asdctool.impl.migration.Migration1707Task;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-
-import java.util.List;
-import java.util.Optional;
-
-@Component("migration1707")
-public class Migration1707 {
-
- private static Logger LOGGER = LoggerFactory.getLogger(Migration1707.class);
-
- private List<Migration1707Task> migrations;
-
- public Migration1707(List<Migration1707Task> migrations) {
- this.migrations = migrations;
- }
-
- public boolean migrate() {
- int startMigrationFrom = Optional.ofNullable(ConfigurationManager.getConfigurationManager().getConfiguration().getStartMigrationFrom()).orElse(0);
- List<Migration1707Task> migrations = this.migrations.subList(startMigrationFrom, this.migrations.size());
- for (Migration1707Task migration : migrations) {
- LOGGER.info(String.format("Starting migration. %s", migration.description()));
- boolean migrationCompletedSuccessfully = migration.migrate();
- if (!migrationCompletedSuccessfully) {
- LOGGER.error(String.format("Migration of class %s has failed.", migration.getClass()));
- return false;
- }
- LOGGER.info(String.format("Completed migration. %s", migration.description()));
- }
- return true;
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707ArtifactUuidFix.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707ArtifactUuidFix.java
deleted file mode 100644
index b3f138241e..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707ArtifactUuidFix.java
+++ /dev/null
@@ -1,585 +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.migration.v1707;
-
-import java.io.BufferedWriter;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import 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.GroupDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
-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.datatypes.tosca.ToscaDataDefinition;
-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.ComponentParametersView;
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
-import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-import org.openecomp.sdc.common.api.Constants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import fj.data.Either;
-
-@org.springframework.stereotype.Component("migration1707UuidFix")
-public class Migration1707ArtifactUuidFix {
-
- @Autowired
- private TitanDao titanDao;
-
- @Autowired
- private ToscaOperationFacade toscaOperationFacade;
-
- private static Logger log = LoggerFactory.getLogger(Migration1707ArtifactUuidFix.class.getName());
-
- public boolean migrate(String fixComponent, String runMode) {
- List<Resource> vfLst = new ArrayList<>();
- List<Service> serviceList = new ArrayList<>();
-
- long time = System.currentTimeMillis();
-
- if (fixComponent.equals("vf_only")) {
- if (fetchFaultVf(fixComponent, vfLst, time) == false) {
- return false;
- }
- } else {
- if (fetchServices(fixComponent, serviceList, time) == false) {
- return false;
- }
- }
- if (runMode.equals("service_vf") || runMode.equals("fix")) {
- log.info("Mode {}. Find problem VFs", runMode);
- if (fetchVf(serviceList, vfLst, time) == false) {
- log.info("Mode {}. Find problem VFs finished with failure", runMode);
- return false;
- }
- log.info("Mode {}. Find problem VFs finished with success", runMode);
- }
- if (runMode.equals("fix") || runMode.equals("fix_only_services")) {
- log.info("Mode {}. Start fix", runMode);
- if (fix(vfLst, serviceList) == false) {
- log.info("Mode {}. Fix finished with failure", runMode);
- return false;
- }
- log.info("Mode {}. Fix finished with success", runMode);
- }
-
- return true;
- }
-
- private boolean fetchFaultVf(String fixComponent, List<Resource> vfLst, long time) {
- log.info("Find fault VF ");
- Writer writer = null;
- try {
- String fileName = "fault_" + time + ".csv";
- writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"));
- writer.write("vf name, vf id, state, version\n");
-
- Map<GraphPropertyEnum, Object> hasProps = new HashMap<>();
- hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
- hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF.name());
-
- Map<GraphPropertyEnum, Object> hasNotProps = new HashMap<>();
- hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
- log.info("Try to fetch resources with properties {} and not {}", hasProps, hasNotProps);
-
- Either<List<GraphVertex>, TitanOperationStatus> servicesByCriteria = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll);
- if (servicesByCriteria.isRight()) {
- log.info("Failed to fetch resources {}", servicesByCriteria.right().value());
- return false;
- }
- List<GraphVertex> resources = servicesByCriteria.left().value();
- for (GraphVertex gv : resources) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreComponentInstances(false);
- filter.setIgnoreArtifacts(false);
- filter.setIgnoreGroups(false);
-
- Either<Resource, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(gv.getUniqueId());
- if (toscaElement.isRight()) {
- log.info("Failed to fetch resources {} {}", gv.getUniqueId(), toscaElement.right().value());
- return false;
- }
-
- Resource resource = toscaElement.left().value();
- String resourceName = resource.getName();
- Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts();
- List<GroupDefinition> groups = resource.getGroups();
- if (groups == null || groups.isEmpty()) {
- log.info("No groups for resource {} id {} ", resourceName, gv.getUniqueId());
- continue;
- }
- boolean isProblematic = false;
- for (GroupDefinition gr : groups) {
- if (gr.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
- if (isProblematicGroup(gr, resourceName, deploymentArtifacts)) {
- isProblematic = true;
- break;
- }
- }
- }
- if (isProblematic) {
- vfLst.add(resource);
- writeModuleResultToFile(writer, resource, null);
- writer.flush();
- }
- titanDao.commit();
- }
-
- } catch (Exception e) {
- log.info("Failed to fetch vf resources ", e);
- return false;
- } finally {
- titanDao.commit();
- try {
- writer.flush();
- writer.close();
- } catch (Exception ex) {
- /* ignore */}
- }
- return true;
- }
-
- private boolean fetchVf(List<Service> serviceList, List<Resource> vfLst, long time) {
- log.info("Find problem VF ");
- if (serviceList.isEmpty()) {
- log.info("No services as input");
- return true;
- }
- Writer writer = null;
- try {
- String fileName = "problemVf_" + time + ".csv";
- writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"));
- writer.write("vf name, vf id, state, version, example service name\n");
- Set<String> vfIds = new HashSet<>();
- for (Service service : serviceList) {
- List<ComponentInstance> componentInstances = service.getComponentInstances();
- for (ComponentInstance ci : componentInstances) {
- if (!vfIds.contains(ci.getComponentUid())) {
- vfIds.add(ci.getComponentUid());
- Either<Resource, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(ci.getComponentUid());
- if (toscaElement.isRight()) {
- log.info("Failed to fetch resource {} {}", ci.getComponentUid(), toscaElement.right().value());
- return false;
- }
- Resource resource = toscaElement.left().value();
- vfLst.add(resource);
- writeModuleResultToFile(writer, resource, service);
- writer.flush();
- titanDao.commit();
- }
- }
- }
- log.info("output file with list of Vf : {}", fileName);
- } catch (Exception e) {
- log.info("Failed to fetch services ", e);
- return false;
- } finally {
- titanDao.commit();
- try {
- writer.flush();
- writer.close();
- } catch (Exception ex) {
- /* ignore */}
- }
- return true;
- }
-
- private boolean fetchServices(String fixServices, List<Service> serviceList, long time) {
- log.info("Find problem Services {}", fixServices);
- Writer writer = null;
-
- try {
- String fileName = "problemService_" + time + ".csv";
- writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "utf-8"));
- writer.write("service name, service id, state, version\n");
-
- Map<GraphPropertyEnum, Object> hasProps = new HashMap<>();
- hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
- if (fixServices.equals("distributed_only")) {
- hasProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
- hasProps.put(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTED.name());
- }
-
- Map<GraphPropertyEnum, Object> hasNotProps = new HashMap<>();
- hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
- log.info("Try to fetch services with properties {} and not {}", hasProps, hasNotProps);
-
- Either<List<GraphVertex>, TitanOperationStatus> servicesByCriteria = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, hasNotProps, JsonParseFlagEnum.ParseAll);
- if (servicesByCriteria.isRight()) {
- log.info("Failed to fetch services {}", servicesByCriteria.right().value());
- return false;
- }
- List<GraphVertex> services = servicesByCriteria.left().value();
- for (GraphVertex gv : services) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreComponentInstances(false);
- filter.setIgnoreArtifacts(false);
- filter.setIgnoreGroups(false);
-
- Either<Service, StorageOperationStatus> toscaElement = toscaOperationFacade.getToscaElement(gv.getUniqueId());
- if (toscaElement.isRight()) {
- log.info("Failed to fetch service {} {}", gv.getUniqueId(), toscaElement.right().value());
- return false;
- }
- Service service = toscaElement.left().value();
- List<ComponentInstance> componentInstances = service.getComponentInstances();
- boolean isProblematic = false;
- if (componentInstances == null) {
- log.info("No instances for service {} ", gv.getUniqueId());
- continue;
- }
- String serviceName = (String) gv.getMetadataProperty(GraphPropertyEnum.NAME);
-
- for (ComponentInstance ci : componentInstances) {
- Map<String, ArtifactDefinition> deploymentArtifacts = ci.getDeploymentArtifacts();
- List<GroupInstance> groupInstances = ci.getGroupInstances();
- if (groupInstances == null || groupInstances.isEmpty()) {
- log.info("No instance groups for instance {} in service {} id {} ", ci.getName(), serviceName, gv.getUniqueId());
- continue;
- }
-
- for (GroupInstance gi : groupInstances) {
- if (gi.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
- if (isProblematicGroupInstance(gi, ci.getName(), serviceName, deploymentArtifacts)) {
- isProblematic = true;
- break;
- }
- }
- }
- if (isProblematic) {
- serviceList.add(service);
- writeModuleResultToFile(writer, service, null);
- writer.flush();
- break;
- }
- }
- titanDao.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();
- try {
- writer.flush();
- writer.close();
- } catch (Exception ex) {
- /* ignore */}
- }
- return true;
- }
-
- private boolean isProblematicGroup(GroupDefinition gr, String resourceName, Map<String, ArtifactDefinition> deploymentArtifacts) {
- List<String> artifacts = gr.getArtifacts();
- List<String> artifactsUuid = gr.getArtifactsUuid();
-
- if ((artifactsUuid == null || artifactsUuid.isEmpty()) && (artifacts == null || artifacts.isEmpty())) {
- log.info("No groups in resource {} ", resourceName);
- return false;
- }
- if (artifacts.size() < artifactsUuid.size()) {
- log.info(" artifacts.size() < artifactsUuid.size() group {} in resource {} ", gr.getName(), resourceName);
- return true;
- }
- if (artifacts.size() > 0 && (artifactsUuid == null || artifactsUuid.isEmpty())) {
- log.info(" artifacts.size() > 0 && (artifactsUuid == null || artifactsUuid.isEmpty() group {} in resource {} ", gr.getName(), resourceName);
- return true;
- }
- if (artifactsUuid.contains(null)) {
- log.info(" artifactsUuid.contains(null) group {} in resource {} ", gr.getName(), resourceName);
- return true;
- }
-
- for (String artifactId : artifacts) {
- String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
- ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactlabel);
- if (artifactDefinition == null) {
- log.info(" artifactDefinition == null label {} group {} in resource {} ", artifactlabel, gr.getName(), resourceName);
- return true;
- }
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactDefinition.getArtifactType());
- if (artifactType != ArtifactTypeEnum.HEAT_ENV) {
- if (!artifactId.equals(artifactDefinition.getUniqueId())) {
- log.info(" !artifactId.equals(artifactDefinition.getUniqueId() artifact {} artId {} group {} in resource {} ", artifactlabel, artifactId, gr.getName(), resourceName);
- return true;
- }
- if (!artifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
- log.info(" artifactsUuid.contains(artifactDefinition.getArtifactUUID() label {} group {} in resource {} ", artifactlabel, gr.getName(), resourceName);
- return true;
- }
- }
- }
- return false;
- }
-
- private boolean isProblematicGroupInstance(GroupInstance gi, String instName, String servicename, Map<String, ArtifactDefinition> deploymentArtifacts) {
- List<String> artifacts = gi.getArtifacts();
- List<String> artifactsUuid = gi.getArtifactsUuid();
- List<String> instArtifactsUuid = gi.getGroupInstanceArtifactsUuid();
-
- if ((artifactsUuid == null || artifactsUuid.isEmpty()) && (artifacts == null || artifacts.isEmpty())) {
- log.info("No instance groups for instance {} in service {} ", instName, servicename);
- return false;
- }
- if (artifacts.size() < artifactsUuid.size()) {
- log.info(" artifacts.size() < artifactsUuid.size() inst {} in service {} ", instName, servicename);
- return true;
- }
- if (artifacts.size() > 0 && (artifactsUuid == null || artifactsUuid.isEmpty())) {
- log.info(" artifacts.size() > 0 && (artifactsUuid == null || artifactsUuid.isEmpty() inst {} in service {} ", instName, servicename);
- return true;
- }
- if (artifactsUuid.contains(null)) {
- log.info(" artifactsUuid.contains(null) inst {} in service {} ", instName, servicename);
- return true;
- }
-
- for (String artifactId : artifacts) {
- String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
- ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactlabel);
- if (artifactDefinition == null) {
- log.info(" artifactDefinition == null label {} inst {} in service {} ", artifactlabel, instName, servicename);
- return true;
- }
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactDefinition.getArtifactType());
- if (artifactType != ArtifactTypeEnum.HEAT_ENV) {
- if (!artifactId.equals(artifactDefinition.getUniqueId())) {
- log.info(" !artifactId.equals(artifactDefinition.getUniqueId() artifact {} artId {} inst {} in service {} ", artifactlabel, artifactId, instName, servicename);
- return true;
- }
- if (!artifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
- log.info(" artifactsUuid.contains(artifactDefinition.getArtifactUUID() label {} inst {} in service {} ", artifactlabel, instName, servicename);
- return true;
- }
- } else {
- if (!instArtifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
- log.info(" instArtifactsUuid.contains(artifactDefinition.getArtifactUUID() label {} inst {} in service {} ", artifactlabel, instName, servicename);
- return true;
- }
- }
- }
- return false;
- }
-
- private boolean fix(List<Resource> vfLst, List<Service> serviceList) {
- boolean res = true;
-
- if (vfLst != null && !vfLst.isEmpty()) {
- res = fixVf(vfLst);
- if (res) {
- for (Component component : vfLst) {
- TopologyTemplate topologyTemplate = ModelConverter.convertToToscaElement(component);
- Map<String, GroupDataDefinition> groups = topologyTemplate.getGroups();
- res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.GROUPS, EdgeLabelEnum.GROUPS, groups);
- }
- }
- }
-
- if (res == true && serviceList != null && !serviceList.isEmpty()) {
- res = fixServices(serviceList);
- if (res) {
- for (Component component : serviceList) {
- TopologyTemplate topologyTemplate = ModelConverter.convertToToscaElement(component);
- Map<String, MapGroupsDataDefinition> groups = topologyTemplate.getInstGroups();
- res = fixDataOnGraph(component.getUniqueId(), VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, groups);
- }
- }
- }
-
- return res;
- }
-
- private <T extends ToscaDataDefinition> boolean fixDataOnGraph(String componentId, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, T> groups) {
- boolean res = true;
- Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
- if (getResponse.isRight()) {
- log.debug("Couldn't fetch component unique id {}, error: {}", componentId, getResponse.right().value());
- res = false;
-
- }
- if (res) {
- GraphVertex componentVertex = getResponse.left().value();
-
- GraphVertex toscaDataVertex = null;
- Either<GraphVertex, TitanOperationStatus> groupVertexEither = titanDao.getChildVertex(componentVertex, edgeLabelEnum, JsonParseFlagEnum.ParseJson);
- if (groupVertexEither.isRight()) {
- res = false;
- log.debug("failed to get child {} vertex for component unique id {}, error: {}", edgeLabelEnum, componentId, groupVertexEither.right().value());
- }
- if (res) {
- toscaDataVertex = groupVertexEither.left().value();
- toscaDataVertex.setJson(groups);
- Either<GraphVertex, TitanOperationStatus> updatevertexEither = titanDao.updateVertex(toscaDataVertex);
- if (updatevertexEither.isRight()) {
- log.debug("failed to update vertex for component unique id {}, error: {}", componentId, updatevertexEither.right().value());
- titanDao.rollback();
- return false;
- }
- }
- }
-
- titanDao.commit();
-
- return res;
- }
-
- private boolean fixServices(List<Service> serviceList) {
- for (Service service : serviceList) {
- log.debug("Migration1707ArtifactUuidFix fix service: id {}, name {} ", service.getUniqueId(), service.getName());
- List<ComponentInstance> instances = service.getComponentInstances();
- for (ComponentInstance instance : instances) {
- Map<String, ArtifactDefinition> artifactsMap = instance.getDeploymentArtifacts();
- List<GroupInstance> groupsList = instance.getGroupInstances();
- if (groupsList != null && artifactsMap != null) {
- for (GroupInstance group : groupsList) {
- if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
- log.debug("Migration1707ArtifactUuidFix fix group: resource id {}, group name {} ", service.getUniqueId(), group.getName());
- List<String> groupArtifacts = new ArrayList<String>(group.getArtifacts());
-
- group.getArtifacts().clear();
- group.getArtifactsUuid().clear();
- group.getGroupInstanceArtifacts().clear();
- group.getGroupInstanceArtifactsUuid().clear();
-
- for (String artifactId : groupArtifacts) {
- String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
- log.debug("Migration1707ArtifactUuidFix fix group: group name {} artifactId for fix {} artifactlabel {} ", group.getName(), artifactId, artifactlabel);
- if (!artifactlabel.isEmpty() && artifactsMap.containsKey(artifactlabel)) {
- ArtifactDefinition artifact = artifactsMap.get(artifactlabel);
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
- String correctArtifactId = artifact.getUniqueId();
- String correctArtifactUUID = artifact.getArtifactUUID();
- if (artifactType != ArtifactTypeEnum.HEAT_ENV) {
-
- log.debug("Migration1707ArtifactUuidFix fix group: group name {} correct artifactId {} artifactUUID {} ", group.getName(), correctArtifactId, correctArtifactUUID);
- group.getArtifacts().add(correctArtifactId);
- if (correctArtifactUUID != null && !correctArtifactUUID.isEmpty()) {
- group.getArtifactsUuid().add(correctArtifactUUID);
- }
- } else {
- log.debug("Migration1707ArtifactUuidFix fix group: group name {} correct artifactId {} artifactUUID {} ", group.getName(), correctArtifactId, correctArtifactUUID);
- group.getGroupInstanceArtifacts().add(correctArtifactId);
- if (correctArtifactUUID != null && !correctArtifactUUID.isEmpty()) {
- group.getGroupInstanceArtifactsUuid().add(correctArtifactUUID);
- }
- }
- }
- }
- }
- }
- }
- }
-
- }
- return true;
-
- }
-
- private boolean fixVf(List<Resource> vfLst) {
- for (Resource resource : vfLst) {
- log.debug("Migration1707ArtifactUuidFix fix resource: id {}, name {} ", resource.getUniqueId(), resource.getName());
- Map<String, ArtifactDefinition> artifactsMap = resource.getDeploymentArtifacts();
- List<GroupDefinition> groupsList = resource.getGroups();
- if (groupsList != null && artifactsMap != null) {
- for (GroupDefinition group : groupsList) {
- if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) && group.getArtifacts() != null) {
- log.debug("Migration1707ArtifactUuidFix fix group: resource id {}, group name {} ", resource.getUniqueId(), group.getName());
- List<String> groupArtifacts = new ArrayList<String>(group.getArtifacts());
- group.getArtifacts().clear();
- group.getArtifactsUuid().clear();
- for (String artifactId : groupArtifacts) {
- String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
- log.debug("Migration1707ArtifactUuidFix fix group: group name {} artifactId for fix {} artifactlabel {} ", group.getName(), artifactId, artifactlabel);
- if (!artifactlabel.isEmpty() && artifactsMap.containsKey(artifactlabel)) {
- ArtifactDefinition artifact = artifactsMap.get(artifactlabel);
- String correctArtifactId = artifact.getUniqueId();
- String correctArtifactUUID = artifact.getArtifactUUID();
- log.debug("Migration1707ArtifactUuidFix fix group: group name {} correct artifactId {} artifactUUID {} ", group.getName(), correctArtifactId, correctArtifactUUID);
- group.getArtifacts().add(correctArtifactId);
- if (correctArtifactUUID != null && !correctArtifactUUID.isEmpty()) {
- group.getArtifactsUuid().add(correctArtifactUUID);
- }
-
- }
- }
- }
- }
- }
-
- }
-
- return true;
- }
-
- private String findArtifactLabelFromArtifactId(String artifactId) {
- String artifactLabel = "";
-
- int index = artifactId.lastIndexOf(".");
- if (index > 0 && index + 1 < artifactId.length())
- artifactLabel = artifactId.substring(index + 1);
- return artifactLabel;
- }
-
- private void writeModuleResultToFile(Writer writer, org.openecomp.sdc.be.model.Component component, Service service) {
- try {
- // "service name, service id, state, version
- StringBuffer sb = new StringBuffer(component.getName());
- sb.append(",").append(component.getUniqueId()).append(",").append(component.getLifecycleState()).append(",").append(component.getVersion());
- if (service != null) {
- sb.append(",").append(service.getName());
- }
- sb.append("\n");
- writer.write(sb.toString());
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707Config.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707Config.java
deleted file mode 100644
index 36919d7520..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707Config.java
+++ /dev/null
@@ -1,279 +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.migration.v1707;
-
-
-import java.util.List;
-
-import org.openecomp.sdc.asdctool.impl.migration.Migration1707Task;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.*;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.FulfilledCapabilitiesMigrationService;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.FulfilledRequirementsMigrationService;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.RequirementsCapabilitiesMigrationService;
-import org.openecomp.sdc.be.dao.TitanClientStrategy;
-import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
-import org.openecomp.sdc.be.model.DerivedNodeTypeResolver;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations;
-import org.openecomp.sdc.be.model.jsontitan.operations.CategoryOperation;
-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.ToscaDataOperation;
-import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
-import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
-import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator;
-import org.openecomp.sdc.be.model.operations.impl.ConsumerOperation;
-import org.openecomp.sdc.be.model.operations.impl.ElementOperation;
-import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.model.operations.impl.ToscaDefinitionPathCalculatorImpl;
-import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Primary;
-import org.springframework.core.annotation.Order;
-
-@Configuration
-public class Migration1707Config {
-
-
- @Bean(name = "migration1707")
- public Migration1707 migration1707(List<Migration1707Task> migrations) {
- return new Migration1707(migrations);
- }
-
- @Bean(name = "renameGraphPropertyKeysMigration")
- @Order(1)
- public Migration1707Task renameGraphPropertyKeysMigration() {
- return new RenameGraphPropertyKeys();
- }
-
- @Bean(name = "toscaNamesUpdate")
- @Order(2)
- public Migration1707Task toscaNamesUpdate() {
- return new ToscaNamesUpdate();
- }
-
- @Bean(name = "users-migration")
- @Order(3)
- public Migration1707Task usersMigration() {
- return new UsersMigration();
- }
-
- @Bean(name = "resource-category-migration")
- @Order(4)
- public Migration1707Task resourceCategoriesMigration() {
- return new ResourcesCategoriesMigration();
- }
-
- @Bean(name = "service-category-migration")
- @Order(5)
- public Migration1707Task serviceCategoriesMigration() {
- return new ServiceCategoriesMigration();
- }
-
- @Bean(name = "normatives-migration")
- @Order(6)
- public Migration1707Task normativesMigration() {
- return new NormativesMigration();
- }
-
- @Bean(name = "vf-migration")
- @Order(7)
- public Migration1707Task vfMigration() {
- return new VFResourcesMigration();
- }
-
- @Bean(name = "service-migration")
- @Order(8)
- public Migration1707Task serviceMigration() {
- return new ServicesMigration();
- }
-
- @Bean(name = "consumers-migration")
- @Order(9)
- public Migration1707Task consumersMigration() { return new ConsumersMigration(); }
-
- @Bean(name = "tosca-template-regeneration")
- @Order(10)
- public Migration1707Task ToscaTemplateRegeneration() {
- return new ToscaTemplateRegeneration();
- }
-
- @Bean(name = "distributionStatusUpdate")
- public DistributionStatusUpdate distributionStatusUpdate() {
- return new DistributionStatusUpdate();
- }
-
- @Bean("resource-version-migration")
- public VersionMigration<Resource> resourceVersionMigration() {
- return new ResourceVersionMigration();
- }
-
- @Bean("service-version-migration")
- public VersionMigration<Service> serviceVersionMigration() {
- return new ServiceVersionMigration();
- }
-
- @Bean(name = "normatives-resolver")
- public NormativesResolver normativesResolver() {
- return new NormativesResolver();
- }
-
- @Bean(name = "property-operation-mig")
- public PropertyOperation propertyOperation(@Qualifier("titan-generic-dao-migration") TitanGenericDao titanGenericDao) {
- return new PropertyOperation(titanGenericDao);
- }
-
- @Bean(name = "group-type-operation-mig")
- public GroupTypeOperation groupTypeOperation(@Qualifier("titan-generic-dao-migration") TitanGenericDao titanGenericDao, @Qualifier("property-operation-mig") PropertyOperation propertyOperation) {
- return new GroupTypeOperation(titanGenericDao, propertyOperation);
- }
-
- @Bean(name = "titan-generic-dao-migration")
- public TitanGenericDao titanGenericDaoMigration(@Qualifier("migration-titan-client") TitanGraphClient titanGraphClient) {
- return new TitanGenericDao(titanGraphClient);
- }
-
- @Bean(name = "migration-titan-strategy")
- public TitanClientStrategy migrationStrategy() {
- return new MigrationTitanStrategy();
- }
-
- @Bean(name = "migration-titan-client", initMethod = "createGraph")
- public TitanGraphClient titanMigrationClient(@Qualifier("migration-titan-strategy") TitanClientStrategy titanClientStrategy) {
- return new TitanGraphClient(titanClientStrategy);
- }
-
- @Bean(name = "user-operation-migration")
- public IUserAdminOperation userOperationNewKeySpace(@Qualifier("titan-generic-dao-migration") TitanGenericDao titanGenericDao) {
- return new UserAdminOperation(titanGenericDao);
- }
-
- @Bean(name = "element-operation-migration")
- public IElementOperation elementOperationNewKeyspace(@Qualifier("titan-generic-dao-migration") TitanGenericDao titanGenericDao) {
- return new ElementOperation(titanGenericDao);
- }
-
- @Bean(name = "tosca-operation-facade")
- public ToscaOperationFacade toscaOperationFacade() {
- return new ToscaOperationFacade();
- }
-
- @Bean(name = "node-type-operation")
- public NodeTypeOperation nodeTypeOperation(@Qualifier("mig-derived-resolver") DerivedNodeTypeResolver migrationDerivedNodeTypeResolver) {
- return new NodeTypeOperation(migrationDerivedNodeTypeResolver);
- }
-
- @Bean(name = "topology-template-operation")
- public TopologyTemplateOperation topologyTemplateOperation() {
- return new TopologyTemplateOperation();
- }
-
- @Bean(name = "node-template-operation")
- public NodeTemplateOperation nodeTemplateOperation() {
- return new NodeTemplateOperation();
- }
-
- @Bean(name = "titan-dao")
- public TitanDao titanDao(@Qualifier("migration-titan-client") TitanGraphClient titanGraphClient) {
- return new TitanDao(titanGraphClient);
- }
-
- @Bean(name = "category-operation")
- public CategoryOperation categoryOperation() {
- return new CategoryOperation();
- }
-
- @Bean(name = "artifacts-operation")
- public ArtifactsOperations artifactsOperation() {
- return new ArtifactsOperations();
- }
-
- @Bean(name = "tosca-data-operation")
- public ToscaDataOperation toscaDataOperation() {
- return new ToscaDataOperation();
- }
-
- @Bean(name = "tosca-element-lifecycle-operation")
- public ToscaElementLifecycleOperation toscaElementLifecycleOperation() {
- return new ToscaElementLifecycleOperation();
- }
-
- @Bean(name = "tosca-path-calculator")
- public ToscaDefinitionPathCalculator pathCalculator() {
- return new ToscaDefinitionPathCalculatorImpl();
- }
-
- @Bean(name = "fulfilled-capabilities-mig-service")
- public FulfilledCapabilitiesMigrationService fulfilledCapabilitiesMigService() {
- return new FulfilledCapabilitiesMigrationService();
- }
-
- @Bean(name = "fulfilled-requirements-mig-service")
- public FulfilledRequirementsMigrationService requirementsMigService() {
- return new FulfilledRequirementsMigrationService();
- }
-
- @Bean(name ="req-cap-mig-service")
- public RequirementsCapabilitiesMigrationService reqCapMigService() {
- return new RequirementsCapabilitiesMigrationService();
- }
-
- @Bean(name = "mig-derived-resolver")
- public DerivedNodeTypeResolver migrationDerivedNodeTypeResolver() {
- return new MigrationByIdDerivedNodeTypeResolver();
- }
-
- @Bean(name = "invariant-uuid-resolver")
- public InvariantUUIDResolver invariantUUIDResolver() {
- return new InvariantUUIDResolver();
- }
-
- @Bean(name="consumer-operation-mig")
- @Primary
- public ConsumerOperation consumerOperation(@Qualifier("titan-generic-dao-migration") TitanGenericDao titanGenericDao) {
- return new ConsumerOperation(titanGenericDao);
- }
-
- @Bean(name = "vfModulesPropertiesAdding")
- public VfModulesPropertiesAdding vfModulesPropertiesAdding() {
- return new VfModulesPropertiesAdding();
- }
-
- @Bean(name = "node-template-missing-data-resolver")
- public NodeTemplateMissingDataResolver nodeTemplateMissingDataResolver() {
- return new NodeTemplateMissingDataResolver<>();
- }
-
- @Bean(name = "migration1707MissingInfoFix")
- public Migration1707MissingInfoFix migration1707MissingInfoFix() {
- return new Migration1707MissingInfoFix();
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707MissingInfoFix.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707MissingInfoFix.java
deleted file mode 100644
index ff41f12b8e..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707MissingInfoFix.java
+++ /dev/null
@@ -1,220 +0,0 @@
-package org.openecomp.sdc.asdctool.impl.migration.v1707;
-
-import fj.data.Either;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.NodeTemplateMissingDataResolver;
-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.*;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
-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.*;
-import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
-import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum;
-import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-
-@org.springframework.stereotype.Component("migration1707MissingInfoFix")
-public class Migration1707MissingInfoFix {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(Migration1707MissingInfoFix.class);
-
- @Resource(name = "service-operation")
- private IServiceOperation serviceOperation;
-
- @Resource(name = "node-template-missing-data-resolver")
- private NodeTemplateMissingDataResolver nodeTemplateMissingDataResolver;
-
- @Resource(name = "tosca-operation-facade")
- private ToscaOperationFacade toscaOperations;
-
- @Resource(name = "titan-dao")
- private TitanDao titanDao;
-
-
- public boolean migrate(){
- boolean res = updateVFs();
- if(res)
- res = updateServices();
- return res;
- }
-
- private ComponentParametersView getFilter() {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreComponentInstances(false);
- filter.setIgnoreArtifacts(false);
- filter.setIgnoreGroups(false);
- filter.setIgnoreComponentInstancesInputs(false);
- return filter;
- }
-
- // if new service has VF instances with no groups - try to fetch them from old graph
- private boolean oldServiceModelRequired(Component newService) {
- Predicate<ComponentInstance> vfInstanceWithNoGroups = p -> OriginTypeEnum.VF == p.getOriginType() && (null == p.getGroupInstances() || p.getGroupInstances().isEmpty());
- return null != newService.getComponentInstances() && newService.getComponentInstances().stream()
- .anyMatch(vfInstanceWithNoGroups);
- }
-
-
-
- private List<GraphVertex> fetchVertices(Map<GraphPropertyEnum, Object> hasProps){
- Either<List<GraphVertex>, TitanOperationStatus> componentsByCriteria = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, hasProps, JsonParseFlagEnum.ParseAll);
- if (componentsByCriteria.isRight()) {
- LOGGER.debug("couldn't fetch assets from sdctitan");
- return null;
- }
- return componentsByCriteria.left().value();
- }
-
- private boolean updateVFs() {
-
- boolean res = true;
- Map<GraphPropertyEnum, Object> hasProps = new HashMap<>();
- hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
- hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF.name());
-
- List<GraphVertex> resources = fetchVertices(hasProps);
- if(null == resources)
- return false;
- ComponentParametersView filter = getFilter();
- Map<String, ToscaElement> origCompMap = new HashMap<>();
-
- for (GraphVertex gv : resources) {
- boolean fixed = true;
- Either<Component, StorageOperationStatus> toscaElement = toscaOperations.getToscaElement(gv.getUniqueId(), filter);
- if (toscaElement.isRight()) {
- LOGGER.debug("Failed to fetch resource {} {}", gv.getUniqueId(), toscaElement.right().value());
- return false;
- }
- Component resource = toscaElement.left().value();
- Map<String, Boolean> updateMap = new HashMap<>();
- nodeTemplateMissingDataResolver.updateVFComposition(resource, origCompMap, updateMap);
- if(updateMap.get(JsonConstantKeysEnum.COMPOSITION.name())){
- LOGGER.info("applying instance tosca name fix on VF {}", gv.getUniqueId());
- fixed = toscaOperations.updateComponentInstanceMetadataOfTopologyTemplate(resource).isLeft();
- }
- if(updateMap.get(EdgeLabelEnum.GROUPS.name())) {
- List<GroupDataDefinition> groups = new ArrayList<>(resource.getGroups());
- LOGGER.info("applying groups vertex fix on VF {}", gv.getUniqueId());
- fixed = fixed && toscaOperations.updateGroupsOnComponent(resource, ComponentTypeEnum.RESOURCE, groups).isLeft();
- }
-
- res = res && fixed;
- titanDao.commit();
- }
- return res;
- }
-
- private Map<String, MapPropertiesDataDefinition> buildInstancesInputsMap(Component component){
- Map<String, MapPropertiesDataDefinition> instanceInputsMap = new HashMap<>();
- for (Map.Entry<String, List<ComponentInstanceInput>> entry : component.getComponentInstancesInputs().entrySet()) {
- MapPropertiesDataDefinition inputsMap = new MapPropertiesDataDefinition();
- inputsMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
- instanceInputsMap.put(entry.getKey(), inputsMap);
- }
- return instanceInputsMap;
- }
-
-
-
- private Map<String, MapGroupsDataDefinition> buildGroupInstanceMap(Component component) {
- Map<String, MapGroupsDataDefinition> instGroupsMap = new HashMap<>();
- for (ComponentInstance instance : component.getComponentInstances()) {
- if (instance.getGroupInstances() != null) {
- MapGroupsDataDefinition groupsMap = new MapGroupsDataDefinition();
- groupsMap.setMapToscaDataDefinition(instance.getGroupInstances().stream().map(e -> new GroupInstanceDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
- instGroupsMap.put(instance.getUniqueId(), groupsMap);
- }
- }
- return instGroupsMap;
- }
-
- private <T extends ToscaDataDefinition> boolean updateDataVertex(GraphVertex componentVertex, VertexTypeEnum vertexType, EdgeLabelEnum edgeLabel, Map<String, T> dataMap){
- Either<GraphVertex, TitanOperationStatus> dataVertexEither = titanDao.getChildVertex(componentVertex, edgeLabel, JsonParseFlagEnum.ParseJson);
- if (dataVertexEither.isRight()) {
- if(TitanOperationStatus.NOT_FOUND != dataVertexEither.right().value())
- return false;
- return (nodeTemplateMissingDataResolver.topologyTemplateOperation.assosiateElementToData(componentVertex, vertexType, edgeLabel, dataMap)).isLeft();
- }
- GraphVertex dataVertex = dataVertexEither.left().value();
- dataVertex.setJson(dataMap);
- return (titanDao.updateVertex(dataVertex)).isLeft();
-
- }
-
-
- private boolean updateServices(){
-
- boolean res = true;
- Map<GraphPropertyEnum, Object> hasProps = new HashMap<>();
- hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
-
- List<GraphVertex> componentsByCriteria = fetchVertices(hasProps);
- if(null == componentsByCriteria)
- return false;
-
- ComponentParametersView filter = getFilter();
- Map<String, ToscaElement> origCompMap = new HashMap<>();
-
- Predicate<ComponentInstance> containsGroupInstances = p -> null != p.getGroupInstances() && !p.getGroupInstances().isEmpty();
-
- for (GraphVertex gv : componentsByCriteria) {
-
- boolean fixed = true;
- Either<org.openecomp.sdc.be.model.Service, StorageOperationStatus> toscaElement = toscaOperations.getToscaElement(gv.getUniqueId(), filter);
- if (toscaElement.isRight()) {
- LOGGER.debug("Failed to fetch service {} {}", gv.getUniqueId(), toscaElement.right().value());
- return false;
- }
- Component service = toscaElement.left().value();
- Component oldService = null;
-
- if(oldServiceModelRequired(service)){
- Either<Service, StorageOperationStatus> oldServiceEither = serviceOperation.getService(gv.getUniqueId(), filter, false);
- if (oldServiceEither.isRight()){
- LOGGER.debug("couldn't fetch service {} from old titan", gv.getUniqueId());
- }else {
- oldService = oldServiceEither.left().value();
- oldService = oldService.getComponentInstances().stream().anyMatch(containsGroupInstances) ? oldService : null;
- }
- }
-
- Map<String, Boolean> updateMap = new HashMap<>();
- nodeTemplateMissingDataResolver.updateServiceComposition(service, origCompMap, oldService, updateMap);
- if(updateMap.get(JsonConstantKeysEnum.COMPOSITION.name())) {
- LOGGER.info("applying instance tosca name fix on service {}", gv.getUniqueId());
- fixed = (toscaOperations.updateComponentInstanceMetadataOfTopologyTemplate(service)).isLeft();
- }
- if(updateMap.get(EdgeLabelEnum.INST_GROUPS.name())) {
- Map<String, MapGroupsDataDefinition> groupsMap = buildGroupInstanceMap(service);
- LOGGER.info("applying groups instances vertex fix on service {}", gv.getUniqueId());
- fixed = fixed && updateDataVertex(gv, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, groupsMap);
- }
- if(updateMap.get(EdgeLabelEnum.INST_INPUTS.name())) {
- Map<String, MapPropertiesDataDefinition> instInputs = buildInstancesInputsMap(service);
- LOGGER.info("applying instances inputs vertex fix on service {}", gv.getUniqueId());
- fixed = fixed && updateDataVertex(gv, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, instInputs);
- }
- res = res && fixed;
- titanDao.commit();
- }
- return res;
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707RelationsFix.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707RelationsFix.java
deleted file mode 100644
index 204f0a5fc8..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707RelationsFix.java
+++ /dev/null
@@ -1,151 +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.migration.v1707;
-
-import java.util.EnumMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import org.apache.tinkerpop.gremlin.structure.Direction;
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
-import org.openecomp.sdc.be.dao.jsongraph.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.GraphPropertyEnum;
-import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import fj.data.Either;
-@Component("migration1707relationsFix")
-public class Migration1707RelationsFix {
-
- private static Logger LOGGER = LoggerFactory.getLogger(Migration1707RelationsFix.class);
-
- @Autowired
- private TitanDao titanDao;
-
- public boolean migrate() {
- boolean result = true;
-
- try{
- Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
- propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
- Either<List<GraphVertex>, TitanOperationStatus> getAllTopologyTemplatesRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, null, propsHasNot, JsonParseFlagEnum.ParseMetadata);
- if (getAllTopologyTemplatesRes.isRight() && getAllTopologyTemplatesRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- LOGGER.debug("Failed to fetch all non marked as deleted topology templates , error {}", getAllTopologyTemplatesRes.right().value());
- result = false;
- }
- if(getAllTopologyTemplatesRes.isLeft()){
- fixComponentsRelations(getAllTopologyTemplatesRes.left().value());
- }
- if(result){
- Either<List<GraphVertex>, TitanOperationStatus> getAllNodeTypesRes = titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, null, propsHasNot, JsonParseFlagEnum.ParseMetadata);
- if (getAllNodeTypesRes.isRight() && getAllNodeTypesRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- LOGGER.debug("Failed to fetch all non marked as deleted node types , error {}", getAllNodeTypesRes.right().value());
- result = false;
- }
- if(getAllNodeTypesRes.isLeft()){
- fixComponentsRelations(getAllNodeTypesRes.left().value());
- }
- }
- } catch (Exception e){
- LOGGER.debug("The exception {} occured upon migration 1707 relations fixing. ", e.getMessage());
- e.printStackTrace();
- result = false;
- }
- finally{
- if(result){
- titanDao.commit();
- } else {
- titanDao.rollback();
- }
- }
- return result;
- }
-
- private void fixComponentsRelations(List<GraphVertex> notDeletedComponentVerticies) {
- notDeletedComponentVerticies.stream().forEach(this::fixComponentRelations);
- }
-
- private void fixComponentRelations(GraphVertex componentV) {
- fixCreatorComponentRelation(componentV);
- fixLastModifierComponentRelation(componentV);
- fixStateComponentRelation(componentV);
- }
-
- private void fixStateComponentRelation(GraphVertex componentV) {
- boolean relevantEdgeFound = false;
- Iterator<Edge> edges = componentV.getVertex().edges(Direction.IN, EdgeLabelEnum.STATE.name());
- String getState = (String) componentV.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE);
- while(edges.hasNext()){
- Edge edge = edges.next();
- String edgeState = (String) edge.property(GraphPropertyEnum.STATE.getProperty()).orElse(null);
- if(getState.equals(edgeState) && !relevantEdgeFound){
- relevantEdgeFound = true;
- } else {
- removeEdge(edge);
- }
- }
- }
-
- private void fixCreatorComponentRelation(GraphVertex componentV) {
- boolean relevantUserFound = false;
- Iterator<Edge> edges = componentV.getVertex().edges(Direction.IN, EdgeLabelEnum.CREATOR.name());
- String getCreatorUserId = (String) componentV.getJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR);
- while(edges.hasNext()){
- Edge edge = edges.next();
- String userId = (String) edge.outVertex().property(GraphPropertyEnum.USERID.getProperty()).orElse(null);
- if(getCreatorUserId.equals(userId) && !relevantUserFound){
- relevantUserFound = true;
- } else {
- removeEdge(edge);
- }
- }
- }
-
- private void fixLastModifierComponentRelation(GraphVertex componentV) {
- boolean relevantUserFound = false;
- Iterator<Edge> edges = componentV.getVertex().edges(Direction.IN, EdgeLabelEnum.LAST_MODIFIER.name());
- String getLastUpdaterUserId = (String) componentV.getJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER);
- while(edges.hasNext()){
- Edge edge = edges.next();
- String updaterId = (String) edge.outVertex().property(GraphPropertyEnum.USERID.getProperty()).orElse(null);
- if(getLastUpdaterUserId.equals(updaterId) && !relevantUserFound){
- relevantUserFound = true;
- } else {
- removeEdge(edge);
- }
- }
- }
-
- private void removeEdge(Edge edge) {
- LOGGER.debug("Going to remove edge {} upon migration 1707 relations fixing. ", edge.id());
- edge.remove();
- LOGGER.debug("The edge {} has been removed. ", edge.id());
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707VnfFix.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707VnfFix.java
deleted file mode 100644
index 5d7a887a7f..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707VnfFix.java
+++ /dev/null
@@ -1,120 +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.migration.v1707;
-
-import java.util.EnumMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.tinkerpop.gremlin.structure.Direction;
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
-import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
-import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
-import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
-import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
-import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
-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;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-@Component("migration1707vnfFix")
-public class Migration1707VnfFix{
-
- private static final String VF_MODULES_METADATA = "vfModulesMetadata";
-
- @Autowired
- private TitanDao titanDao;
-
- @Autowired
- private TopologyTemplateOperation topologyTemplateOperation;
-
- private static Logger LOGGER = LoggerFactory.getLogger(Migration1707RelationsFix.class);
-
- public boolean migrate() {
- boolean result = true;
-
- Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
- propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
-
- Map<GraphPropertyEnum, Object> propsHas = new EnumMap<>(GraphPropertyEnum.class);
- propsHas.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
- propsHas.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF.name());
- propsHas.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED);
-
- Either<List<GraphVertex>, TitanOperationStatus> getAllTopologyTemplatesRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, null, propsHasNot, JsonParseFlagEnum.ParseMetadata);
- if (getAllTopologyTemplatesRes.isRight() && getAllTopologyTemplatesRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- LOGGER.debug("Failed to fetch all non marked as deleted topology templates , error {}", getAllTopologyTemplatesRes.right().value());
- result = false;
- }
- List<GraphVertex> metadataVertices = getAllTopologyTemplatesRes.left().value();
- for (GraphVertex metadataV : metadataVertices) {
- Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> dataFromGraph = topologyTemplateOperation.getDataFromGraph(metadataV.getUniqueId(), EdgeLabelEnum.DEPLOYMENT_ARTIFACTS);
- if (dataFromGraph.isLeft()) {
- Map<String, ArtifactDataDefinition> artifacts = dataFromGraph.left().value();
- if (artifacts.containsKey(VF_MODULES_METADATA)) {
- artifacts.remove(VF_MODULES_METADATA);
- Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(metadataV.getUniqueId());
- TitanVertex vertex = vertexById.left().value().getVertex();
- Iterator<Edge> edges = vertex.edges(Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS.name());
- if (edges.hasNext()) {
- Edge edge = edges.next();
- Vertex dataV = edge.inVertex();
-
- String jsonStr;
- try {
- jsonStr = JsonParserUtils.jsonToString(artifacts);
- dataV.property(GraphPropertyEnum.JSON.getProperty(), jsonStr);
- } catch (Exception e) {
- LOGGER.debug("Failed to update deployment artifacts for VF {}", metadataV.getUniqueId());
- }
- }
- }
- }
- TitanOperationStatus commit = titanDao.commit();
- if ( commit != TitanOperationStatus.OK){
- LOGGER.debug("Failed to commit changes for deployment artifacts for VF {} {}", metadataV.getUniqueId(), metadataV.getMetadataProperty(GraphPropertyEnum.NAME));
- }
- }
-
- return result;
- }
-
- public String description() {
- // TODO Auto-generated method stub
- return null;
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationTitanStrategy.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationTitanStrategy.java
deleted file mode 100644
index 0274ca425e..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationTitanStrategy.java
+++ /dev/null
@@ -1,33 +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.migration.v1707;
-
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.dao.TitanClientStrategy;
-
-public class MigrationTitanStrategy implements TitanClientStrategy {
-
- @Override
- public String getConfigFile() {
- return ConfigurationManager.getConfigurationManager().getConfiguration().getTitanMigrationKeySpaceCfgFile();
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationUtils.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationUtils.java
deleted file mode 100644
index 04f810af5e..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/MigrationUtils.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.asdctool.impl.migration.v1707;
-
-import org.apache.commons.lang.enums.Enum;
-import org.openecomp.sdc.asdctool.impl.migration.MigrationException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-public class MigrationUtils {
-
- private static Logger LOGGER = LoggerFactory.getLogger(MigrationUtils.class);
-
- public static boolean handleError(String errorMsg) {
- LOGGER.error(errorMsg);
- return false;
- }
-
- public static <T> T handleError(T errorStatus, String errorMsg) {
- LOGGER.error(errorMsg);
- return errorStatus;
- }
-
- public static <A> A willThrowException(String withMsg) {
- throw new MigrationException(withMsg);
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/RenameGraphPropertyKeys.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/RenameGraphPropertyKeys.java
deleted file mode 100644
index 9f571167db..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/RenameGraphPropertyKeys.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.asdctool.impl.migration.v1707;
-
-import org.openecomp.sdc.asdctool.impl.migration.*;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import java.util.HashMap;
-import java.util.Map;
-
-@Component("renameGraphPropertyKeysMigration")
-public class RenameGraphPropertyKeys implements Migration1707Task {
-
- private final static Map<String, String> KEY_PROPERTIES_TO_RENAME;
-
- @Autowired
- private MigrationOperationUtils migrationUtils;
-
- static {
- KEY_PROPERTIES_TO_RENAME = new HashMap<>();
- KEY_PROPERTIES_TO_RENAME.put("attuid", GraphPropertiesDictionary.USERID.getProperty());
- KEY_PROPERTIES_TO_RENAME.put("pmatt", GraphPropertiesDictionary.PROJECT_CODE.getProperty());
- KEY_PROPERTIES_TO_RENAME.put("attContact", GraphPropertiesDictionary.CONTACT_ID.getProperty());
- KEY_PROPERTIES_TO_RENAME.put("attCreator", GraphPropertiesDictionary.CREATOR_ID.getProperty());
- }
-
- @Override
- public boolean migrate() {
- return migrationUtils.renamePropertyKeys(KEY_PROPERTIES_TO_RENAME);
- }
-
- @Override
- public String description() {
- return MigrationMsg.RENMAE_KEY_PROPERTIES_1707.getMessage();
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaNamesUpdate.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaNamesUpdate.java
deleted file mode 100644
index 665fe15315..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaNamesUpdate.java
+++ /dev/null
@@ -1,388 +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.migration.v1707;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Function;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.commons.lang3.tuple.ImmutableTriple;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.openecomp.sdc.asdctool.impl.migration.Migration1707Task;
-import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.resources.data.AttributeData;
-import org.openecomp.sdc.be.resources.data.AttributeValueData;
-import org.openecomp.sdc.be.resources.data.CapabilityData;
-import org.openecomp.sdc.be.resources.data.CapabilityTypeData;
-import org.openecomp.sdc.be.resources.data.DataTypeData;
-import org.openecomp.sdc.be.resources.data.GroupData;
-import org.openecomp.sdc.be.resources.data.GroupTypeData;
-import org.openecomp.sdc.be.resources.data.InputValueData;
-import org.openecomp.sdc.be.resources.data.InputsData;
-import org.openecomp.sdc.be.resources.data.PolicyTypeData;
-import org.openecomp.sdc.be.resources.data.PropertyData;
-import org.openecomp.sdc.be.resources.data.PropertyValueData;
-import org.openecomp.sdc.be.resources.data.RelationshipInstData;
-import org.openecomp.sdc.be.resources.data.RelationshipTypeData;
-import org.openecomp.sdc.be.resources.data.RequirementData;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-@Component("toscaNamesUpdate")
-public class ToscaNamesUpdate implements Migration1707Task {
- private static Logger log = LoggerFactory.getLogger(ToscaNamesUpdate.class.getName());
-
- @Override
- public String description() {
- return "toscaNamesUpdate";
- }
-
- @Autowired
- protected TitanGenericDao titanGenericDao;
-
- @Override
- public boolean migrate() {
- boolean result = true;
- List<ImmutableTriple<NodeTypeEnum, Class<GraphNode>, Function<GraphNode, ImmutablePair<String, GraphNode>>>> updateInfoList = new ArrayList<>();
- for (NodeTypeEnum nodeType : NodeTypeEnum.values()){
- ImmutableTriple<NodeTypeEnum, Class<GraphNode>, Function<GraphNode, ImmutablePair<String, GraphNode>>> updateInfo = getInfo(nodeType);
- if(null == updateInfo)
- continue;
- updateInfoList.add(updateInfo);
- }
-
- for(ImmutableTriple<NodeTypeEnum, Class<GraphNode>, Function<GraphNode, ImmutablePair<String, GraphNode>>> nodeTypeData : updateInfoList){
- log.debug("before updating namespace on nodeType {}", nodeTypeData.left.getName());
- result = updateNamespaceByNodeType(nodeTypeData);
- if(!result){
- log.debug("alignNamespace procedure failed during execution of updating namespace on nodeType {}", nodeTypeData.left.getName());
- return false;
- }
- }
- return true;
- }
-
- private <T extends GraphNode> ImmutableTriple<NodeTypeEnum, Class<T>, Function<T, ImmutablePair<String, T>>> getInfo(NodeTypeEnum nodeType) {
- switch (nodeType) {
- case Resource:
- Function<ResourceMetadataData, ImmutablePair<String, ResourceMetadataData>> resourceFunc = r -> updateResource(r);
- return new ImmutableTriple(nodeType, ResourceMetadataData.class, resourceFunc);
- case GroupType:
- Function<GroupTypeData, ImmutablePair<String, GroupTypeData>> groupTypeFunc = g -> updateGroupType(g);
- return new ImmutableTriple(nodeType, GroupTypeData.class, groupTypeFunc);
- case Group:
- Function<GroupData, ImmutablePair<String, GroupData>> groupFunc = g -> updateGroupNode(g);
- return new ImmutableTriple(nodeType, GroupData.class, groupFunc);
- case PolicyType:
- Function<PolicyTypeData, ImmutablePair<String , PolicyTypeData>> policyFunc = p -> updatePolicyType(p);
- return new ImmutableTriple(nodeType, PolicyTypeData.class, policyFunc);
- case RelationshipType:
- Function<RelationshipTypeData, ImmutablePair<String, RelationshipTypeData>> relTypeFunc = r -> updateRelationshipType(r);
- return new ImmutableTriple(nodeType, RelationshipTypeData.class, relTypeFunc);
- case RelationshipInst:
- Function<RelationshipInstData, ImmutablePair<String, RelationshipInstData>> relFunc = r -> updateRelationshipNode(r);
- return new ImmutableTriple(nodeType, RelationshipInstData.class, relFunc);
- case Requirement:
- Function<RequirementData, ImmutablePair<String, RequirementData>> reqFunc = r -> updateRequirementType(r);
- return new ImmutableTriple(nodeType, RequirementData.class, reqFunc);
- case CapabilityType:
- Function<CapabilityTypeData, ImmutablePair<String, CapabilityTypeData>> capTypeFunc = c -> updateCapabilityType(c);
- return new ImmutableTriple(nodeType, CapabilityTypeData.class, capTypeFunc);
- case Capability:
- Function<CapabilityData, ImmutablePair<String, CapabilityData>> capFunc = c -> updateCapabilityNode(c);
- return new ImmutableTriple(nodeType, CapabilityData.class, capFunc);
- case Property:
- Function<PropertyData, ImmutablePair<String, PropertyData>> propFunc = p -> updatePropNode(p);
- return new ImmutableTriple(nodeType, PropertyData.class, propFunc);
- case PropertyValue:
- Function<PropertyValueData, ImmutablePair<String, PropertyValueData>> propValueFunc = p -> updatePropValueNode(p);
- return new ImmutableTriple(nodeType, PropertyValueData.class, propValueFunc);
- case Attribute:
- Function<AttributeData, ImmutablePair<String, AttributeData>> attrFunc = a -> updateAttributeNode(a);
- return new ImmutableTriple(nodeType, AttributeData.class, attrFunc);
- case AttributeValue:
- Function<AttributeValueData, ImmutablePair<String, AttributeValueData>> attrValueFunc = a -> updateAttrValueNode(a);
- return new ImmutableTriple(nodeType, AttributeValueData.class, attrValueFunc);
- case Input:
- Function<InputsData, ImmutablePair<String, InputsData>> inputFunc = i -> updateInputNode(i);
- return new ImmutableTriple(nodeType, InputsData.class, inputFunc);
- case InputValue:
- Function<InputValueData, ImmutablePair<String, InputValueData>> inputValueFunc = i -> updateInputValueNode(i);
- return new ImmutableTriple(nodeType, InputValueData.class, inputValueFunc);
- case DataType:
- Function<DataTypeData, ImmutablePair<String, DataTypeData>> dataTypeFunc = d -> updateDataType(d);
- return new ImmutableTriple(nodeType, DataTypeData.class, dataTypeFunc);
- default:
- return null;
- }
-
- }
-
-
-
- private boolean ifRight(TitanOperationStatus status){
- return TitanOperationStatus.NOT_FOUND == status;
- }
-
- private <T extends GraphNode> boolean ifLeft(List<T> allNodes, ImmutableTriple<NodeTypeEnum, Class<T>, Function<T, ImmutablePair<String, T>>> nodeTypeData){
- boolean result = true;
- try {
- for (T node : allNodes) {
- ImmutablePair<String, T> nodeToUpdate = nodeTypeData.right.apply(node);
- Either<T, TitanOperationStatus> updatedNode = updateNodeIncludingUID(nodeToUpdate.left, nodeToUpdate.right, nodeTypeData.middle);
- if (updatedNode.isRight()) {
- result = false;
- break;
- }
- }
- } finally {
- if (!result) {
- titanGenericDao.rollback();
- } else {
- titanGenericDao.commit();
- }
- }
- return result;
- }
-
- private <T extends GraphNode> boolean updateNamespaceByNodeType(ImmutableTriple<NodeTypeEnum, Class<T>, Function<T, ImmutablePair<String, T>>> nodeTypeData) {
- Either<List<T>, TitanOperationStatus> getAllNodes = titanGenericDao.getByCriteria(nodeTypeData.left, null, nodeTypeData.middle);
- return getAllNodes.either(list -> ifLeft(list, nodeTypeData), status -> ifRight(status));
- }
-
- private ImmutablePair<String, ResourceMetadataData> updateResource(ResourceMetadataData resource) {
- String toscaResourceName = updateNamespace(((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).getToscaResourceName());
- ((ResourceMetadataDataDefinition) resource.getMetadataDataDefinition()).setToscaResourceName(toscaResourceName);
- return new ImmutablePair<>((String) resource.getUniqueId(), resource);
- }
-
- private ImmutablePair<String, GroupTypeData> updateGroupType(GroupTypeData group) {
- String originId = group.getUniqueId();
- group.getGroupTypeDataDefinition().setUniqueId(updateNamespace(originId));
- String type = updateNamespace(group.getGroupTypeDataDefinition().getType());
- group.getGroupTypeDataDefinition().setType(type);
- return new ImmutablePair<>(originId, group);
- }
-
- private ImmutablePair<String, GroupData> updateGroupNode(GroupData group) {
- String type = updateNamespace(group.getGroupDataDefinition().getType());
- group.getGroupDataDefinition().setType(type);
- return new ImmutablePair<>((String) group.getUniqueId(), group);
- }
-
-
- private ImmutablePair<String, PolicyTypeData> updatePolicyType(PolicyTypeData policy) {
- String originId = policy.getUniqueId();
- policy.getPolicyTypeDataDefinition().setUniqueId(updateNamespace(originId));
- String type = updateNamespace(policy.getPolicyTypeDataDefinition().getType());
- policy.getPolicyTypeDataDefinition().setType(type);
- return new ImmutablePair<>(originId, policy);
- }
-
- private ImmutablePair<String, RelationshipTypeData> updateRelationshipType(RelationshipTypeData relation) {
- String type = updateNamespace(relation.getRelationshipTypeDataDefinition().getType());
- relation.getRelationshipTypeDataDefinition().setType(type);
- List<String> validSources = relation.getRelationshipTypeDataDefinition().getValidSourceTypes();
- if(null != validSources){
- List<String> validSourceTypes = new ArrayList<>();
- for (String validSourceType : validSources) {
- validSourceTypes.add(updateNamespace(validSourceType));
- }
- relation.getRelationshipTypeDataDefinition().setValidSourceTypes(validSourceTypes);
- }
- return new ImmutablePair<>(relation.getUniqueId(), relation);
- }
-
- private ImmutablePair<String, RelationshipInstData> updateRelationshipNode(RelationshipInstData relation) {
- String type = updateNamespace(relation.getType());
- relation.setType(type);
- return new ImmutablePair<>(relation.getUniqueId(), relation);
- }
-
- private ImmutablePair<String, RequirementData> updateRequirementType(RequirementData req) {
- String node = req.getNode();
- if(null != node)
- req.setNode(updateNamespace(node));
- String type = updateNamespace(req.getRelationshipType());
- req.setRelationshipType(type);
- return new ImmutablePair<>(req.getUniqueId(), req);
- }
-
- private ImmutablePair<String, CapabilityTypeData> updateCapabilityType(CapabilityTypeData capType) {
- String originId = capType.getUniqueId();
- capType.getCapabilityTypeDataDefinition().setUniqueId(updateNamespace(originId));
- String type = updateNamespace(capType.getCapabilityTypeDataDefinition().getType());
- capType.getCapabilityTypeDataDefinition().setType(type);
- List<String> validSources = capType.getCapabilityTypeDataDefinition().getValidSourceTypes();
- if(null != validSources){
- List<String> validSourceTypes = new ArrayList<>();
- for (String validSourceType : validSources) {
- validSourceTypes.add(updateNamespace(validSourceType));
- }
- capType.getCapabilityTypeDataDefinition().setValidSourceTypes(validSourceTypes);
- }
- return new ImmutablePair<>(originId, capType);
-
- }
-
- private ImmutablePair<String, CapabilityData> updateCapabilityNode(CapabilityData capNode) {
- List<String> validSources = capNode.getValidSourceTypes();
- if(null != validSources){
- List<String> validSourceTypes = new ArrayList<>();
- for (String validSourceType : validSources) {
- validSourceTypes.add(updateNamespace(validSourceType));
- }
- capNode.setValidSourceTypes(validSourceTypes);
- }
- return new ImmutablePair<>(capNode.getUniqueId(), capNode);
- }
-
-
- private ImmutablePair<String, PropertyData> updatePropNode(PropertyData propType) {
- String originId = (String)propType.getUniqueId();
- propType.getPropertyDataDefinition().setUniqueId(updateNamespace(originId));
- String type = updateNamespace(propType.getPropertyDataDefinition().getType());
- propType.getPropertyDataDefinition().setType(type);
- if ("list".equalsIgnoreCase(type) || "map".equalsIgnoreCase(type)){
- SchemaDefinition schema = propType.getPropertyDataDefinition().getSchema();
- if(null != schema && null != schema.getProperty())
- handleSchemaTypeDef(schema.getProperty());
- }
- return new ImmutablePair<>(originId, propType);
- }
-
- private ImmutablePair<String, PropertyValueData> updatePropValueNode(PropertyValueData prop) {
- String type = updateNamespace(prop.getType());
- prop.setType(type);
- return new ImmutablePair<>(prop.getUniqueId(), prop);
- }
-
- private ImmutablePair<String, AttributeValueData> updateAttrValueNode(AttributeValueData attr) {
- String type = updateNamespace(attr.getType());
- attr.setType(type);
- return new ImmutablePair<>(attr.getUniqueId(), attr);
- }
-
- private ImmutablePair<String, InputValueData> updateInputValueNode(InputValueData input) {
- String type = updateNamespace(input.getType());
- input.setType(type);
- return new ImmutablePair<>(input.getUniqueId(), input);
- }
-
- private ImmutablePair<String, InputsData> updateInputNode(InputsData input){
- String type = updateNamespace(input.getPropertyDataDefinition().getType());
- input.getPropertyDataDefinition().setType(type);
- if ("list".equalsIgnoreCase(type) || "map".equalsIgnoreCase(type)){
- SchemaDefinition schema = input.getPropertyDataDefinition().getSchema();
- if(null != schema && null != schema.getProperty())
- handleSchemaTypeDef(schema.getProperty());
- }
- return new ImmutablePair<>((String)input.getUniqueId(), input);
- }
-
-
- private void handleSchemaTypeDef(PropertyDataDefinition schemaProp) {
- String schemaType = updateNamespace(schemaProp.getType());
- schemaProp.setType(schemaType);
- }
-
- private ImmutablePair<String, DataTypeData> updateDataType(DataTypeData dataType) {
- String originId = dataType.getUniqueId();
- dataType.getDataTypeDataDefinition().setUniqueId(updateNamespace(originId));
- String name = updateNamespace(dataType.getDataTypeDataDefinition().getName());
- dataType.getDataTypeDataDefinition().setName(name);
- String derivedFromName = updateNamespace(dataType.getDataTypeDataDefinition().getDerivedFromName());
- dataType.getDataTypeDataDefinition().setDerivedFromName(derivedFromName);
- return new ImmutablePair<>(originId, dataType);
-
- }
-
- private ImmutablePair<String, AttributeData> updateAttributeNode(AttributeData attr){
- String type = updateNamespace(attr.getAttributeDataDefinition().getType());
- attr.getAttributeDataDefinition().setType(type);
- if("list".equalsIgnoreCase(type) || "map".equalsIgnoreCase(type)){
- SchemaDefinition schema = attr.getAttributeDataDefinition().getSchema();
- if(null != schema && null != schema.getProperty())
- handleSchemaTypeDef(schema.getProperty());
- }
- return new ImmutablePair<>(attr.getUniqueId(), attr);
- }
-
-
-
- private String updateNamespace(String oldName) {
- if (oldName == null) {
- return null;
- }
- String name = oldName.replace("com.att.d2.", "org.openecomp.");
- // correcting naming convention
- return name.replace("org.openecomp.resources.", "org.openecomp.resource.");
- }
-
- private <T extends GraphNode> T onSuccess(TitanVertex vertex, GraphNode node, Class<T> clazz){
- Map<String, Object> newProp = titanGenericDao.getProperties(vertex);
- return GraphElementFactory.createElement(node.getLabel(), GraphElementTypeEnum.Node, newProp, clazz);
- }
-
- private <T extends GraphNode> Either<T, TitanOperationStatus> handleNode(Vertex vertex, GraphNode node, Class<T> clazz){
- try {
-
- Map<String, Object> mapProps = node.toGraphMap();
-
- for (Map.Entry<String, Object> entry : mapProps.entrySet()) {
- vertex.property(entry.getKey(), entry.getValue());
- }
-
- Either<TitanVertex, TitanOperationStatus> vertexByPropertyAndLabel = titanGenericDao.getVertexByProperty(node.getUniqueIdKey(), node.getUniqueId());
- return vertexByPropertyAndLabel.either(v -> Either.left(onSuccess(v, node, clazz)), status -> Either.right(status));
-
- } catch (Exception e) {
- if (log.isDebugEnabled()) {
- log.debug("Failed to update node for {}", node.getKeyValueId(), e);
- }
- return Either.right(TitanGraphClient.handleTitanException(e));
- }
- }
-
- private <T extends GraphNode> Either<T, TitanOperationStatus> updateNodeIncludingUID(String originId, GraphNode node, Class<T> clazz) {
- Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(node.getUniqueIdKey(), originId);
- return vertexByProperty.either(vertex -> handleNode(vertex, node, clazz), status -> Either.right(status));
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaTemplateRegeneration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaTemplateRegeneration.java
deleted file mode 100644
index 7d009fe158..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/ToscaTemplateRegeneration.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.asdctool.impl.migration.v1707;
-
-import java.util.EnumMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.collections.CollectionUtils;
-import org.openecomp.sdc.asdctool.impl.migration.Migration1707Task;
-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.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.ArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
-import org.openecomp.sdc.be.resources.data.ESArtifactData;
-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.util.GeneralUtility;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import fj.data.Either;
-
-@Component("toscaTemplateRegeneration")
-public class ToscaTemplateRegeneration implements Migration1707Task {
-
- private static Logger LOGGER = LoggerFactory.getLogger(ToscaTemplateRegeneration.class);
-
- @Autowired
- protected ArtifactCassandraDao artifactCassandraDao;
-
- @Autowired
- private ToscaExportHandler toscaExportUtils;
-
- @Autowired
- private ToscaOperationFacade toscaOperationFacade;
-
- @Override
- public boolean migrate() {
- boolean result = true;
- Either<List<GraphVertex>, StorageOperationStatus> getAllCertifiedComponentsRes;
- try{
- getAllCertifiedComponentsRes = getAllCertifiedComponents();
- if(getAllCertifiedComponentsRes.isRight()){
- result = false;
- }
- if(result && CollectionUtils.isNotEmpty(getAllCertifiedComponentsRes.left().value())){
- result = regenerateToscaTemplateArtifacts(getAllCertifiedComponentsRes.left().value());
- }
- } catch(Exception e){
- LOGGER.error("The exception {} has been occured upon tosca template regeneration migration. ", e);
- result = false;
- } finally {
- if(result){
- toscaOperationFacade.commit();
- } else {
- toscaOperationFacade.rollback();
- }
- }
- return result;
- }
-
- private boolean regenerateToscaTemplateArtifacts(List<GraphVertex> components) {
- boolean result = true;
- for(GraphVertex componentV : components){
- String componentId = componentV.getUniqueId();
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getComponentsRes = toscaOperationFacade.getToscaElement(componentId);
- if (getComponentsRes.isRight()) {
- result = false;
- break;
- }
- if(getComponentsRes.left().value().getToscaArtifacts()!=null && getComponentsRes.left().value().getToscaArtifacts().containsKey(ToscaExportHandler.ASSET_TOSCA_TEMPLATE)){
- result = regenerateToscaTemplateArtifact(getComponentsRes.left().value(), componentV);
- }
- if(result){
- toscaOperationFacade.commit();
- } else {
- toscaOperationFacade.rollback();
- break;
- }
- }
- return result;
- }
-
- @SuppressWarnings("unchecked")
- private boolean regenerateToscaTemplateArtifact(org.openecomp.sdc.be.model.Component parent, GraphVertex parentV) {
- boolean result = true;
- Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = null;
- ArtifactDataDefinition data = null;
- LOGGER.debug("tosca artifact generation");
- Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
- if (exportComponent.isRight()) {
- LOGGER.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value());
- result = false;
- }
- if(result){
- LOGGER.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
- toscaDataVertexRes = toscaOperationFacade.getTitanDao().getChildVertex(parentV, EdgeLabelEnum.TOSCA_ARTIFACTS, JsonParseFlagEnum.ParseJson);
- if(toscaDataVertexRes.isRight()){
- LOGGER.debug("Failed to fetch tosca data vertex {} for component {}. Status is {}", EdgeLabelEnum.TOSCA_ARTIFACTS, parent.getUniqueId(), exportComponent.right().value());
- result = false;
- }
- }
- if(result){
- data = parent.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
- data.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(exportComponent.left().value().getMainYaml().getBytes()));
-
- ((Map<String, ArtifactDataDefinition>) toscaDataVertexRes.left().value().getJson()).put(ToscaExportHandler.ASSET_TOSCA_TEMPLATE, data);
-
- Either<GraphVertex, TitanOperationStatus> updateVertexRes = toscaOperationFacade.getTitanDao().updateVertex(toscaDataVertexRes.left().value());
- if(updateVertexRes.isRight()){
- result = false;
- }
- }
- if(result){
- ESArtifactData artifactData = new ESArtifactData(data.getEsId(), exportComponent.left().value().getMainYaml().getBytes());
- CassandraOperationStatus status = artifactCassandraDao.saveArtifact(artifactData);
- if(status != CassandraOperationStatus.OK){
- result = false;
- }
- }
- return result;
- }
-
- public Either<List<GraphVertex>, StorageOperationStatus> getAllCertifiedComponents() {
-
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
- List<GraphVertex> components = null;
- Either<List<GraphVertex>, TitanOperationStatus> getVerticiesRes = toscaOperationFacade.getTitanDao().getByCriteria(null, propertiesToMatch,JsonParseFlagEnum.NoParse);
-
- if (getVerticiesRes.isRight() && getVerticiesRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- LOGGER.debug("Failed to fetch all certified components. Status is {}", getVerticiesRes.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticiesRes.right().value()));
- }
- if(getVerticiesRes.isLeft()){
- components = getVerticiesRes.left().value();
- }
- return Either.left(components);
- }
-
- @Override
- public String description() {
- return "toscaTemplateRegeneration";
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/VfModulesPropertiesAdding.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/VfModulesPropertiesAdding.java
deleted file mode 100644
index 89ac6f7cb6..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/VfModulesPropertiesAdding.java
+++ /dev/null
@@ -1,257 +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.migration.v1707;
-
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
-import javax.annotation.Resource;
-
-import org.apache.commons.collections.CollectionUtils;
-import org.openecomp.sdc.asdctool.impl.migration.v1702.DataTypesUpdate;
-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.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
-import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.GroupInstanceProperty;
-import org.openecomp.sdc.be.model.GroupProperty;
-import org.openecomp.sdc.be.model.GroupTypeDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.jsontitan.operations.BaseOperation;
-import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
-import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.GroupTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.resources.data.PropertyData;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import fj.data.Either;
-
-@Component("vfModulesPropertiesAdding")
-public class VfModulesPropertiesAdding {
-
- private static Logger LOGGER = LoggerFactory.getLogger(VfModulesPropertiesAdding.class);
-
- @Autowired
- private ToscaOperationFacade toscaOperationFacade;
-
- @Autowired
- private TopologyTemplateOperation topologyTemplateOperation;
-
- @Resource(name ="group-type-operation-mig")
- private GroupTypeOperation groupTypeOperation;
-
- @Resource(name = "property-operation-mig")
- private PropertyOperation propertyOperation;
-
-
- public boolean migrate(String groupsTypeYmlFilePath) {
- LOGGER.debug("Going to add new properties to vfModules. ");
- boolean result = true;
- GroupTypeDefinition vfModule;
- Either<List<GraphVertex>, TitanOperationStatus> getAllTopologyTemplatesRes = null;
- String vfModuleUid = "org.openecomp.groups.VfModule.1.0.grouptype";
- Either<GroupTypeDefinition, TitanOperationStatus> getGroupTypeVfModuleRes ;
- List<PropertyDefinition> updatedProperties = null;
- try{
- LOGGER.debug("Going to fetch {}. ", vfModuleUid);
- getGroupTypeVfModuleRes = groupTypeOperation.getGroupTypeByUid(vfModuleUid);
-
- if(getGroupTypeVfModuleRes.isRight() && getGroupTypeVfModuleRes.right().value() != TitanOperationStatus.NOT_FOUND){
- LOGGER.debug("Failed to fetch the group type {}. The status is {}. ", vfModuleUid, getGroupTypeVfModuleRes.right().value());
- result = false;
- }
- if(getGroupTypeVfModuleRes.isRight() && getGroupTypeVfModuleRes.right().value() == TitanOperationStatus.NOT_FOUND){
- LOGGER.debug("The group type with id {} was not found. Skipping adding the new properties. ", vfModuleUid);
- return true;
- }
- if(result){
- LOGGER.debug("Going to add the new properties {} to org.openecomp.groups.VfModule.1.0.grouptype. ");
- vfModule = getGroupTypeVfModuleRes.left().value();
- updatedProperties = getAllVfModuleTypePropertiesFromYaml(groupsTypeYmlFilePath);
- result = addNewPropertiesToGroupType(vfModule, getNewVfModuleTypeProperties(updatedProperties, vfModule));
- if(!result){
- LOGGER.debug("Failed to add the new properties {} to org.openecomp.groups.VfModule.1.0.grouptype. ");
- }
- }
- if(result && CollectionUtils.isNotEmpty(updatedProperties)){
- Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
- propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
- getAllTopologyTemplatesRes = toscaOperationFacade.getTitanDao().getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, null, propsHasNot, JsonParseFlagEnum.ParseAll);
- if (getAllTopologyTemplatesRes.isRight() && getAllTopologyTemplatesRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- LOGGER.debug("Failed to fetch all non marked topology templates , propsHasNot {}, error {}", propsHasNot, getAllTopologyTemplatesRes.right().value());
- result = false;
- }
- }
- if(result && getAllTopologyTemplatesRes!=null && getAllTopologyTemplatesRes.isLeft()){
- result = addNewVfModulesProperties(getAllTopologyTemplatesRes.left().value(), updatedProperties);
- }
- } catch (Exception e){
- result = false;
- }
- finally{
- if(result){
- toscaOperationFacade.commit();
- } else {
- toscaOperationFacade.rollback();
- }
- }
- return result;
- }
-
- private boolean addNewVfModulesProperties(List<GraphVertex> components, List<PropertyDefinition> updatedProperties) {
- boolean result = true;
- for(GraphVertex component : components){
- LOGGER.debug("Going to add the new properties {} to component {}. ", updatedProperties, component.getUniqueId());
- result = addNewPropertiesToVfModules(component, updatedProperties);
- if(!result){
- LOGGER.debug("Failed to add the new properties {} to component {}. ", updatedProperties, component.getUniqueId());
- break;
- }
- toscaOperationFacade.commit();
- }
- return result;
- }
-
- private boolean addNewPropertiesToVfModules(GraphVertex componentV, List<PropertyDefinition> updatedProperties) {
- boolean result = true;
- List<GroupDefinition> vfModules = null;
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getToscaElementRes = toscaOperationFacade.getToscaElement(componentV);
- if(getToscaElementRes.isRight()){
- LOGGER.debug("Failed to fetch the component {}. ", componentV.getUniqueId());
- result = false;
- }
- else if(CollectionUtils.isNotEmpty(getToscaElementRes.left().value().getGroups())){
- vfModules = getToscaElementRes.left().value().getGroups().stream().filter(g -> g.getType().equals(BaseOperation.VF_MODULE)).collect(Collectors.toList());
- }
- if(vfModules != null){
- vfModules.forEach(vfModule -> addAllNewProperties(vfModule.getProperties(), updatedProperties));
- StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, vfModules, JsonPresentationFields.NAME);
- if(status!= StorageOperationStatus.OK){
- LOGGER.debug("Failed to add the new properties {} to groups of component {}. ", updatedProperties, componentV.getUniqueId());
- result = false;
- }
- }
- if(result && CollectionUtils.isNotEmpty(getToscaElementRes.left().value().getComponentInstances())){
- result = addPropertiesToVfModuleInstances(getToscaElementRes.left().value(), componentV, updatedProperties);
- }
- return result;
- }
-
- private void addAllNewProperties(List<PropertyDataDefinition> vfModuleProperties, List<PropertyDefinition> updatedProperties) {
- Map<String, PropertyDataDefinition> propertiesMap = vfModuleProperties.stream().collect(Collectors.toMap(p->p.getName(), p->p));
-
- for(PropertyDefinition property : updatedProperties){
- if(!propertiesMap.containsKey(property.getName())){
- vfModuleProperties.add(property);
- }
- }
- }
-
- private boolean addPropertiesToVfModuleInstances(org.openecomp.sdc.be.model.Component component, GraphVertex componentV, List<PropertyDefinition> updatedProperties) {
- boolean result = true;
- List<GroupInstance> vfModuleInstances;
- List<String> pathKeys;
- LOGGER.debug("Going to add the new properties {} to group instances of component {}. ", updatedProperties, componentV.getUniqueId());
- for(ComponentInstance componentInstance : component.getComponentInstances()){
- vfModuleInstances = null;
- if(CollectionUtils.isNotEmpty(componentInstance.getGroupInstances())){
- vfModuleInstances = componentInstance.getGroupInstances()
- .stream()
- .filter(gi -> gi.getType().equals(BaseOperation.VF_MODULE))
- .collect(Collectors.toList());
- }
- if(vfModuleInstances != null){
- for(GroupInstance vfModuleInstance :vfModuleInstances){
- addAllNewProperties(vfModuleInstance.getProperties(),updatedProperties);
- pathKeys = new ArrayList<>();
- pathKeys.add(componentInstance.getUniqueId());
- StorageOperationStatus status = topologyTemplateOperation
- .updateToscaDataDeepElementOfToscaElement(componentV, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, vfModuleInstance, pathKeys, JsonPresentationFields.NAME);
- if(status!= StorageOperationStatus.OK){
- result = false;
- LOGGER.debug("Failed to add the new properties {} to group instances of component {}. ", updatedProperties, componentV.getUniqueId());
- break;
- }
- }
- if(!result){
- LOGGER.debug("Failed to add the new properties {} to group instances of component {}. ", updatedProperties, componentV.getUniqueId());
- break;
- }
- }
- }
- return result;
- }
-
- private boolean addNewPropertiesToGroupType(GroupTypeDefinition vfModule, List<PropertyDefinition> newProperties) {
- boolean result = true;
- Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesRes = propertyOperation
- .addPropertiesToElementType(vfModule.getUniqueId(), NodeTypeEnum.GroupType, newProperties);
- if(addPropertiesRes.isRight()){
- result = false;
- }
- return result;
- }
-
- private List<PropertyDefinition> getAllVfModuleTypePropertiesFromYaml(String groupsTypeYmlFilePath) {
- List<DataTypeDefinition> groupTypes = DataTypesUpdate.extractDataTypesFromYaml(groupsTypeYmlFilePath);
- DataTypeDefinition vfModule = groupTypes.stream().filter(g -> g.getName().equals(BaseOperation.VF_MODULE)).findFirst().orElse(null);
- return vfModule.getProperties();
- }
-
- private List<PropertyDefinition> getNewVfModuleTypeProperties(List<PropertyDefinition> allVfModuleTypeProperties, GroupTypeDefinition vfModule) {
- Map<String, PropertyDefinition> existingVfModuleTypeProperties = vfModule.getProperties()
- .stream()
- .collect(Collectors.toMap(p -> p.getName(), p -> p));
-
- List<PropertyDefinition> newGroupTypeProperties = new ArrayList<>();
- for(PropertyDefinition property : allVfModuleTypeProperties){
- if(!existingVfModuleTypeProperties.containsKey(property.getName())){
- newGroupTypeProperties.add(property);
- }
- }
- return newGroupTypeProperties;
- }
-
- public String description() {
- return "vfModulesPropertiesAdding";
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/CategoriesUtils.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/CategoriesUtils.java
deleted file mode 100644
index 44d95395d0..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/CategoriesUtils.java
+++ /dev/null
@@ -1,45 +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.migration.v1707.jsonmodel;
-
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-
-import java.util.List;
-import java.util.stream.Collectors;
-
-public class CategoriesUtils {
-
- public static final String OLD_CATEGORY_ID_SUB_STR = "layer";
-
- public static List<CategoryDefinition> filterOldCategories(List<CategoryDefinition> categoryDefinitions) {
- return categoryDefinitions.stream()
- .filter(categoryDefinition -> !categoryDefinition.getUniqueId().contains(OLD_CATEGORY_ID_SUB_STR))
- .collect(Collectors.toList());
- }
-
- public static List<SubCategoryDefinition> filterOldSubCategories(List<SubCategoryDefinition> categoryDefinitions) {
- return categoryDefinitions.stream()
- .filter(categoryDefinition -> !categoryDefinition.getUniqueId().contains(OLD_CATEGORY_ID_SUB_STR))
- .collect(Collectors.toList());
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ComponentMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ComponentMigration.java
deleted file mode 100644
index 7603a5704a..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ComponentMigration.java
+++ /dev/null
@@ -1,132 +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.migration.v1707.jsonmodel;
-
-import fj.data.Either;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.relations.RequirementsCapabilitiesMigrationService;
-import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
-import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
-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.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-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.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.migration.MigrationMalformedDataLogger;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-import org.openecomp.sdc.common.api.Constants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.annotation.Resource;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils.handleError;
-
-public abstract class ComponentMigration <T extends Component> extends JsonModelMigration<T> {
-
- private static Logger LOGGER = LoggerFactory.getLogger(ComponentMigration.class);
-
- @Resource(name = "tosca-operation-facade")
- private ToscaOperationFacade toscaOperations;
-
- @Resource(name = "req-cap-mig-service")
- RequirementsCapabilitiesMigrationService<T> requirementsCapabilitiesMigrationService;
-
- @Resource(name = "invariant-uuid-resolver")
- private InvariantUUIDResolver <T> invariantUUIDResolver;
-
- @Resource(name = "node-template-missing-data-resolver")
- private NodeTemplateMissingDataResolver nodeTemplateMissingDataResolver;
-
- @Override
- boolean save(T element) {
- LOGGER.debug(String.format("creating component %s in new graph", element.getName()));
- return toscaOperations.createToscaComponent(element)
- .either(savedNode -> true,
- err -> handleError(String.format("failed to create component %s with id %s. reason: %s", element.getName(), element.getUniqueId(), err.name())));
- }
-
- @Override
- Either<T, StorageOperationStatus> getElementFromNewGraph(T element) {
- LOGGER.debug(String.format("checking if component %s already exists on new graph", element.getName()));
- return toscaOperations.getToscaElement(element.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
- }
-
- @Override
- public StorageOperationStatus getNotFoundErrorStatus() {
- return StorageOperationStatus.NOT_FOUND;
- }
-
- @Override
- void doPreMigrationOperation(List<T> elements) {
- setMissingInvariantUids(elements);
- }
-
- //some invariants uids are missing in production
- private void setMissingInvariantUids(List<T> components) {
- List<T> missingInvariantCmpts = getComponentsWithNoInvariantUUIDs(components);
- for (T missingInvariantCmpt : missingInvariantCmpts) {
- missingInvariantCmpt.setInvariantUUID(invariantUUIDResolver.resolveInvariantUUID(components, missingInvariantCmpt));
- }
- }
-
- private List<T> getComponentsWithNoInvariantUUIDs(List<T> components) {
- List<T> cmptsWithoutInvariant = components.stream().filter(c -> c.getInvariantUUID() == null).collect(Collectors.toList());
- if (!cmptsWithoutInvariant.isEmpty()) {
- cmptsWithoutInvariant.forEach(cmpt -> MigrationMalformedDataLogger.logMalformedDataMsg(String.format("component %s is missing invariant uuid", cmpt.getUniqueId())));
- }
- return cmptsWithoutInvariant;
- }
-
-
- protected void setMissingTemplateInfo(List<T> components) {
- Map<String, ToscaElement> origCompMap = new HashMap<>();
- for (T component : components) {
- List<ComponentInstance> instances = component.getComponentInstances();
- if(null != instances) {
- for (ComponentInstance instance : instances) {
- nodeTemplateMissingDataResolver.resolveNodeTemplateInfo(instance, origCompMap, component);
- nodeTemplateMissingDataResolver.fixVFGroupInstances(component, instance);
- }
- }
- nodeTemplateMissingDataResolver.fixVFGroups(component);
- }
- }
-
-
-
-
-
-
-
-
-
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ConsumersMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ConsumersMigration.java
deleted file mode 100644
index c455f870aa..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ConsumersMigration.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
-
-import fj.data.Either;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ConsumerOperation;
-import org.openecomp.sdc.be.resources.data.ConsumerData;
-
-import javax.annotation.Resource;
-import java.util.List;
-
-import static org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils.handleError;
-
-public class ConsumersMigration extends JsonModelMigration<ConsumerData> {
-
- @Resource(name = "consumer-operation")
- private ConsumerOperation consumerOperation;
-
- @Resource(name = "consumer-operation-mig")
- private ConsumerOperation consumerOperationMigration;
-
- @Override
- Either<List<ConsumerData>, ?> getElementsToMigrate() {
- return consumerOperation.getAll();
- }
-
- @Override
- Either<ConsumerData, ?> getElementFromNewGraph(ConsumerData element) {
- return consumerOperationMigration.getCredentials(element.getConsumerDataDefinition().getConsumerName());
- }
-
- @Override
- boolean save(ConsumerData element) {
- return consumerOperationMigration.createCredentials(element)
- .either(savedConsumer -> true,
- err -> handleError(String.format("failed to save consumer %s. reason: %s", element.getConsumerDataDefinition().getConsumerName(), err.name())));
- }
-
- @Override
- StorageOperationStatus getNotFoundErrorStatus() {
- return StorageOperationStatus.NOT_FOUND;
- }
-
- @Override
- public String description() {
- return "consumers migration";
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/InvariantUUIDResolver.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/InvariantUUIDResolver.java
deleted file mode 100644
index e26a01e1b4..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/InvariantUUIDResolver.java
+++ /dev/null
@@ -1,61 +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.migration.v1707.jsonmodel;
-
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.operations.migration.MigrationMalformedDataLogger;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Optional;
-
-public class InvariantUUIDResolver <T extends Component> {
-
- public String resolveInvariantUUID(List<T> components, T missingInvariantCmpt) {
- String uuid = missingInvariantCmpt.getUUID();
- String systemName = missingInvariantCmpt.getSystemName();
- String invariantUid = findInvariantUUidByAllVersionsMap(missingInvariantCmpt, components).orElseGet(() -> findInvariantUUidByUUIDOrSystemName(components, uuid, systemName));
- if (invariantUid == null) {
- MigrationMalformedDataLogger.logMalformedDataMsg(String.format("could not find invariant uuid for component %s with id %s", missingInvariantCmpt.getName(), missingInvariantCmpt.getUniqueId()));
- }
- return invariantUid;
- }
-
- private String findInvariantUUidByUUIDOrSystemName(List<T> components, String uuid, String systemName) {
- return components.stream()
- .filter(c -> c.getUUID().equals(uuid) || c.getSystemName().equals(systemName))
- .map(Component::getInvariantUUID)
- .filter(c -> c != null)
- .findAny().orElse(null);
- }
-
- private Optional<String> findInvariantUUidByAllVersionsMap(T component, List<T> allComponents) {
- if (component.getAllVersions() == null) return Optional.empty();
- Collection<String> allVersionsComponentIds = component.getAllVersions().values();
- return allComponents.stream().filter(c -> allVersionsComponentIds.contains(c.getUniqueId()))
- .map(Component::getInvariantUUID)
- .filter(c -> c != null)
- .findAny();
-
-
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/JsonModelMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/JsonModelMigration.java
deleted file mode 100644
index 76c66de1c9..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/JsonModelMigration.java
+++ /dev/null
@@ -1,112 +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.migration.v1707.jsonmodel;
-
-import fj.data.Either;
-import org.openecomp.sdc.asdctool.impl.migration.Migration1707Task;
-import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils;
-import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.annotation.Resource;
-import java.util.List;
-
-public abstract class JsonModelMigration<T> implements Migration1707Task {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(JsonModelMigration.class);
-
- @Resource(name = "titan-dao")
- TitanDao titanDao;
-
- @Override
- public boolean migrate() {
- Either<List<T>, ?> elementsToMigrate = getElementsToMigrate();
- return elementsToMigrate.either(this::migrateElementsToNewGraph,
- errorStatus -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_RETRIEVE_NODES.getMessage(errorStatus.toString())));
- }
-
- boolean doPostSaveOperation(T element) {
- return true;
- }
-
- boolean doPostMigrateOperation(List<T> elements) {
- return true;
- }
-
- void doPreMigrationOperation(List<T> elements){}
-
- private boolean migrateElementsToNewGraph(List<T> elementsToMigrate) {
- LOGGER.info(this.description() + ": starting to migrate elements to new graph. elements to migrate: {}", elementsToMigrate.size());
- doPreMigrationOperation(elementsToMigrate);
- for (T node : elementsToMigrate) {
- boolean migratedSuccessfully = migrateElement(node);
- if (!migratedSuccessfully) {
- titanDao.rollback();
- return false;
- }
- titanDao.commit();
- }
- return postMigrate(elementsToMigrate);
- }
-
- private boolean migrateElement(T node) {
- boolean savedSuccessfully = saveElementIfNotExists(node);
- return savedSuccessfully && doPostSaveOperation(node);
- }
-
- private boolean postMigrate(List<T> elements) {
- boolean postMigrateSuccessfully = doPostMigrateOperation(elements);
- if (!postMigrateSuccessfully) {
- titanDao.rollback();
- return false;
- }
- titanDao.commit();
- return true;
- }
-
- private boolean saveElementIfNotExists(T element) {
- return isExists(element).either(isExist -> isExist || save(element),
- status -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_GET_NODE_FROM_GRAPH.getMessage(status.toString())));
- }
-
-
- private Either<Boolean, ?> isExists(T element) {
- Either<T, ?> byId = getElementFromNewGraph(element);
- return byId.either(existingVal -> Either.left(true),
- this::getEitherNotExistOrErrorStatus);
- }
-
- private <S> Either<Boolean, S> getEitherNotExistOrErrorStatus(S status) {
- return status == getNotFoundErrorStatus() ? Either.left(false) : Either.right(status);
- }
-
- abstract Either<List<T>, ?> getElementsToMigrate();
-
- abstract Either<T, ?> getElementFromNewGraph(T element);
-
- abstract boolean save(T element);
-
- abstract <S extends Enum> S getNotFoundErrorStatus();
-
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/MigrationByIdDerivedNodeTypeResolver.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/MigrationByIdDerivedNodeTypeResolver.java
deleted file mode 100644
index 066ab9a01a..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/MigrationByIdDerivedNodeTypeResolver.java
+++ /dev/null
@@ -1,43 +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.migration.v1707.jsonmodel;
-
-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.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.model.DerivedNodeTypeResolver;
-
-import javax.annotation.Resource;
-import java.util.Collections;
-import java.util.List;
-
-public class MigrationByIdDerivedNodeTypeResolver implements DerivedNodeTypeResolver {
-
- @Resource(name = "titan-dao")
- private TitanDao titanDao;
-
- @Override
- public Either<List<GraphVertex>, TitanOperationStatus> findDerivedResources(String parentResource) {
- return titanDao.getVertexById(parentResource, JsonParseFlagEnum.ParseMetadata).left().map(Collections::singletonList);
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NodeTemplateMissingDataResolver.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NodeTemplateMissingDataResolver.java
deleted file mode 100644
index c83421066c..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NodeTemplateMissingDataResolver.java
+++ /dev/null
@@ -1,353 +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.migration.v1707.jsonmodel;
-import fj.data.Either;
-import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
-import fj.data.Either;
-import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-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.enums.JsonConstantKeysEnum;
-import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
-import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-import org.openecomp.sdc.common.api.Constants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.*;
-import java.util.stream.Collectors;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-
-public class NodeTemplateMissingDataResolver <T extends Component> {
-
- private static Logger LOGGER = LoggerFactory.getLogger(NodeTemplateMissingDataResolver.class);
-
- @Resource(name = "tosca-element-lifecycle-operation")
- private ToscaElementLifecycleOperation lifecycleOperation;
-
- @Resource(name = "topology-template-operation")
- public TopologyTemplateOperation topologyTemplateOperation;
-
- public void resolveNodeTemplateInfo(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap, T component) {
- lifecycleOperation.resolveToscaComponentName(vfInst, origCompMap);
- if(OriginTypeEnum.VF == vfInst.getOriginType()) {
- collectVFInstanceInputs(component, origCompMap, vfInst);
- }
- }
-
-
-
-
- public void updateServiceComposition(Component component, Map<String, ToscaElement> origCompMap, Component oldModelService, Map<String, Boolean> updateMap){
-
- boolean composition = false;
- boolean instInputs = false;
- boolean instGroups = false;
- List<ComponentInstance> instances = component.getComponentInstances();
- if(null != instances) {
- for (ComponentInstance instance : instances) {
- composition = composition || lifecycleOperation.resolveToscaComponentName(instance, origCompMap);
- if(OriginTypeEnum.VF == instance.getOriginType()) {
- instInputs = instInputs || collectVFInstanceInputs(component, origCompMap, instance);
- instGroups = instGroups || resolveInstGroupsFromOldTitanGraphAndApplyFix(component, instance, oldModelService);
- }
- }
- }
- updateMap.put(JsonConstantKeysEnum.COMPOSITION.name(), composition);
- updateMap.put(EdgeLabelEnum.INST_INPUTS.name(), instInputs);
- updateMap.put(EdgeLabelEnum.INST_GROUPS.name(), instGroups);
- }
-
-
- public void updateVFComposition(Component component, Map<String, ToscaElement> origCompMap, Map<String, Boolean> updateMap) {
-
- boolean composition = false;
- boolean groups = fixVFGroups(component);
- List<ComponentInstance> instances = component.getComponentInstances();
- if(null != instances) {
- for (ComponentInstance instance : instances) {
- composition = composition || lifecycleOperation.resolveToscaComponentName(instance, origCompMap);
- }
- }
- updateMap.put(JsonConstantKeysEnum.COMPOSITION.name(), composition);
- updateMap.put(EdgeLabelEnum.GROUPS.name(), groups);
- }
-
-
-
- private boolean resolveInstGroupsFromOldTitanGraphAndApplyFix(Component component, ComponentInstance instance, Component oldService){
-
- boolean res = false;
- //info already exists, apply fix if needed
- if(null != instance.getGroupInstances() && !instance.getGroupInstances().isEmpty()) {
- res = fixVFGroupInstances(component, instance);
- //get group instances from old model
- }else if(null != oldService){
- ComponentInstance origInstance = oldService.getComponentInstances().stream()
- .filter(p -> instance.getUniqueId().equals(p.getUniqueId()))
- .findAny().orElse(null);
- if(null != origInstance && null != origInstance.getGroupInstances()) {
- fixVFGroupInstances(oldService, origInstance);
- instance.setGroupInstances(origInstance.getGroupInstances());
- res = true;
- }
- }
- return res;
- }
-
- private boolean collectVFInstanceInputs(Component component, Map<String, ToscaElement> origCompMap, ComponentInstanceDataDefinition vfInst) {
- boolean res = false;
- String ciUid = vfInst.getUniqueId();
- String origCompUid = vfInst.getComponentUid();
- if(null == component.getComponentInstancesInputs())
- component.setComponentInstancesInputs(new HashMap<>());
- Map<String, List<ComponentInstanceInput>> componentInstInputs = component.getComponentInstancesInputs();
- Either<ToscaElement, StorageOperationStatus> origComp = fetchToscaElement(origCompMap, vfInst, origCompUid);
- if(origComp.isRight())
- return false;
- Map<String, PropertyDataDefinition> origVFInputs = ((TopologyTemplate)origComp.left().value()).getInputs();
- if (origVFInputs != null && !origVFInputs.isEmpty()) {
- res = true;
- Map<String, ComponentInstanceInput> collectedVFInputs = origVFInputs.values().stream()
- .collect(Collectors.toMap(PropertyDataDefinition::getName, ComponentInstanceInput::new));
-
- List<ComponentInstanceInput> instInputList = componentInstInputs.get(ciUid);
- Map<String, ComponentInstanceInput> existingInstInputs = ToscaDataDefinition.listToMapByName(instInputList);
- collectedVFInputs.putAll(existingInstInputs);
- List<ComponentInstanceInput> mergedList = new ArrayList<>(collectedVFInputs.values());
- componentInstInputs.put(ciUid, mergedList);
- }
- return res;
- }
-
- private Either<ToscaElement, StorageOperationStatus> fetchToscaElement(Map<String, ToscaElement> origCompMap, ComponentInstanceDataDefinition vfInst, String origCompUid) {
- Either<ToscaElement, StorageOperationStatus> origCompEither;
- if (!origCompMap.containsKey(origCompUid)) {
- origCompEither = topologyTemplateOperation.getToscaElement(origCompUid);
- if (origCompEither.isRight()) {
- LOGGER.error("failed to fetch Tosca element {} with id {}", vfInst.getComponentName(), origCompUid);
- return origCompEither;
- }
- origCompMap.put(origCompUid, origCompEither.left().value());
- }
- return Either.left(origCompMap.get(origCompUid));
- }
-
- protected boolean isProblematicGroup(GroupDefinition gr, String resourceName, Map<String, ArtifactDefinition> deploymentArtifacts) {
- List<String> artifacts = gr.getArtifacts();
- List<String> artifactsUuid = gr.getArtifactsUuid();
-
- if ((artifactsUuid == null || artifactsUuid.isEmpty()) && (artifacts == null || artifacts.isEmpty())) {
- LOGGER.debug("No groups in resource {} ", resourceName);
- return false;
- }
- if (artifacts.size() < artifactsUuid.size()) {
- LOGGER.debug(" artifacts.size() < artifactsUuid.size() group {} in resource {} ", gr.getName(), resourceName);
- return true;
- }
- if (artifacts.size() > 0 && (artifactsUuid == null || artifactsUuid.isEmpty())) {
- LOGGER.debug(" artifacts.size() > 0 && (artifactsUuid == null || artifactsUuid.isEmpty() group {} in resource {} ", gr.getName(), resourceName);
- return true;
- }
- if (artifactsUuid.contains(null)) {
- LOGGER.debug(" artifactsUuid.contains(null) group {} in resource {} ", gr.getName(), resourceName);
- return true;
- }
-
- for (String artifactId : artifacts) {
- String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
- ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactlabel);
- if (artifactDefinition == null) {
- LOGGER.debug(" artifactDefinition == null label {} group {} in resource {} ", artifactlabel, gr.getName(), resourceName);
- return true;
- }
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactDefinition.getArtifactType());
- if (artifactType != ArtifactTypeEnum.HEAT_ENV) {
- if (!artifactId.equals(artifactDefinition.getUniqueId())) {
- LOGGER.debug(" !artifactId.equals(artifactDefinition.getUniqueId() artifact {} artId {} group {} in resource {} ", artifactlabel, artifactId, gr.getName(), resourceName);
- return true;
- }
- if (!artifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
- LOGGER.debug(" artifactsUuid.contains(artifactDefinition.getArtifactUUID() label {} group {} in resource {} ", artifactlabel, gr.getName(), resourceName);
- return true;
- }
- }
- }
- return false;
- }
-
- protected boolean isProblematicGroupInstance(GroupInstance gi, String instName, String servicename, Map<String, ArtifactDefinition> deploymentArtifacts) {
- List<String> artifacts = gi.getArtifacts();
- List<String> artifactsUuid = gi.getArtifactsUuid();
- List<String> instArtifactsUuid = gi.getGroupInstanceArtifactsUuid();
-
- if ((artifactsUuid == null || artifactsUuid.isEmpty()) && (artifacts == null || artifacts.isEmpty())) {
- LOGGER.debug("No instance groups for instance {} in service {} ", instName, servicename);
- return false;
- }
- if (artifacts.size() < artifactsUuid.size()) {
- LOGGER.debug(" artifacts.size() < artifactsUuid.size() inst {} in service {} ", instName, servicename);
- return true;
- }
- if (artifacts.size() > 0 && (artifactsUuid == null || artifactsUuid.isEmpty())) {
- LOGGER.debug(" artifacts.size() > 0 && (artifactsUuid == null || artifactsUuid.isEmpty() inst {} in service {} ", instName, servicename);
- return true;
- }
- if (artifactsUuid.contains(null)) {
- LOGGER.debug(" artifactsUuid.contains(null) inst {} in service {} ", instName, servicename);
- return true;
- }
-
- for (String artifactId : artifacts) {
- String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
- ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactlabel);
- if (artifactDefinition == null) {
- LOGGER.debug(" artifactDefinition == null label {} inst {} in service {} ", artifactlabel, instName, servicename);
- return true;
- }
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactDefinition.getArtifactType());
- if (artifactType != ArtifactTypeEnum.HEAT_ENV) {
- if (!artifactId.equals(artifactDefinition.getUniqueId())) {
- LOGGER.debug(" !artifactId.equals(artifactDefinition.getUniqueId() artifact {} artId {} inst {} in service {} ", artifactlabel, artifactId, instName, servicename);
- return true;
- }
- if (!artifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
- LOGGER.debug(" artifactsUuid.contains(artifactDefinition.getArtifactUUID() label {} inst {} in service {} ", artifactlabel, instName, servicename);
- return true;
- }
- } else {
- if (!instArtifactsUuid.contains(artifactDefinition.getArtifactUUID())) {
- LOGGER.debug(" instArtifactsUuid.contains(artifactDefinition.getArtifactUUID() label {} inst {} in service {} ", artifactlabel, instName, servicename);
- return true;
- }
- }
- }
- return false;
- }
-
- private String findArtifactLabelFromArtifactId(String artifactId) {
- String artifactLabel = "";
-
- int index = artifactId.lastIndexOf(".");
- if (index > 0 && index + 1 < artifactId.length())
- artifactLabel = artifactId.substring(index + 1);
- return artifactLabel;
- }
-
- public boolean fixVFGroups(Component component){
- boolean res = false;
-
- Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
- List<GroupDefinition> groups = component.getGroups();
- if (groups == null || groups.isEmpty()) {
- LOGGER.debug("No groups in component {} id {} ", component.getName(), component.getUniqueId());
- return res;
- }
-
- for (GroupDefinition group : groups) {
- if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE) && deploymentArtifacts != null) {
- if (isProblematicGroup(group, component.getName(), deploymentArtifacts)) {
- res = true;
- List<String> groupArtifacts = null == group.getArtifacts()? new ArrayList<>() : new ArrayList<>(group.getArtifacts());
- group.setArtifacts(new ArrayList<>());
- group.setArtifactsUuid(new ArrayList<>());
- for (String artifactId : groupArtifacts) {
- String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
- LOGGER.debug("fix group: group name {} artifactId for fix {} artifactlabel {} ", group.getName(), artifactId, artifactlabel);
- if (!artifactlabel.isEmpty() && deploymentArtifacts.containsKey(artifactlabel)) {
- ArtifactDefinition artifact = deploymentArtifacts.get(artifactlabel);
- String correctArtifactId = artifact.getUniqueId();
- String correctArtifactUUID = artifact.getArtifactUUID();
- LOGGER.debug(" fix group: group name {} correct artifactId {} artifactUUID {} ", group.getName(), correctArtifactId, correctArtifactUUID);
- group.getArtifacts().add(correctArtifactId);
- if (correctArtifactUUID != null && !correctArtifactUUID.isEmpty()) {
- group.getArtifactsUuid().add(correctArtifactUUID);
- }
- }
- }
- }
- }
- }
- return res;
- }
-
- public boolean fixVFGroupInstances(Component component, ComponentInstance instance){
- boolean res = false;
-
- Map<String, ArtifactDefinition> deploymentArtifacts = instance.getDeploymentArtifacts();
- List<GroupInstance> groupInstances = instance.getGroupInstances();
- if (groupInstances == null || groupInstances.isEmpty()) {
- LOGGER.debug("No instance groups for instance {} in service {} id {} ", instance.getName(), component.getName(), component.getUniqueId());
- return res;
- }
- for (GroupInstance group : groupInstances) {
- if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
- if (isProblematicGroupInstance(group, instance.getName(), component.getName(), deploymentArtifacts)) {
- res = true;
- LOGGER.debug("Migration1707ArtifactUuidFix fix group: resource id {}, group name {} ", component.getUniqueId(), group.getName());
- List<String> groupArtifacts = null == group.getArtifacts()? new ArrayList<>() : new ArrayList<>(group.getArtifacts());
- group.setArtifacts(new ArrayList<>());
- group.setArtifactsUuid(new ArrayList<>());
- group.setGroupInstanceArtifacts(new ArrayList<>());
- group.setGroupInstanceArtifactsUuid(new ArrayList<>());
-
- for (String artifactId : groupArtifacts) {
- String artifactlabel = findArtifactLabelFromArtifactId(artifactId);
- LOGGER.debug("Migration1707ArtifactUuidFix fix group: group name {} artifactId for fix {} artifactlabel {} ", group.getName(), artifactId, artifactlabel);
- if (!artifactlabel.isEmpty() && deploymentArtifacts.containsKey(artifactlabel)) {
- ArtifactDefinition artifact = deploymentArtifacts.get(artifactlabel);
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
- String correctArtifactId = artifact.getUniqueId();
- String correctArtifactUUID = artifact.getArtifactUUID();
- if (artifactType != ArtifactTypeEnum.HEAT_ENV) {
-
- LOGGER.debug("Migration1707ArtifactUuidFix fix group: group name {} correct artifactId {} artifactUUID {} ", group.getName(), correctArtifactId, correctArtifactUUID);
- group.getArtifacts().add(correctArtifactId);
- if (correctArtifactUUID != null && !correctArtifactUUID.isEmpty()) {
- group.getArtifactsUuid().add(correctArtifactUUID);
- }
- } else {
- LOGGER.debug("Migration1707ArtifactUuidFix fix group: group name {} correct artifactId {} artifactUUID {} ", group.getName(), correctArtifactId, correctArtifactUUID);
- group.getGroupInstanceArtifacts().add(correctArtifactId);
- if (correctArtifactUUID != null && !correctArtifactUUID.isEmpty()) {
- group.getGroupInstanceArtifactsUuid().add(correctArtifactUUID);
- }
- }
- }
- }
- }
- }
- }
- return res;
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesMigration.java
deleted file mode 100644
index 1717b1fa83..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesMigration.java
+++ /dev/null
@@ -1,86 +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.migration.v1707.jsonmodel;
-
-import fj.data.Either;
-import jersey.repackaged.com.google.common.collect.Sets;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.List;
-import java.util.Optional;
-import java.util.Set;
-
-public class NormativesMigration extends ComponentMigration<Resource> {
-
- private static Logger LOGGER = LoggerFactory.getLogger(NormativesMigration.class);
- private static final String JCP_VERSION_PROPERTY = "jcp-version";
- private static final Set<String> e2eMalformedVfcs = Sets.newHashSet("59da26b4-edd0-4412-a2e6-d6711f376340");
-
- @javax.annotation.Resource(name = "normatives-resolver")
- private NormativesResolver normativesResolver;
-
- @javax.annotation.Resource(name = "resource-version-migration")
- private VersionMigration<Resource> versionMigration;
-
- @Override
- public String description() {
- return "migration of node types";
- }
-
- @Override
- Either<List<Resource>, ?> getElementsToMigrate() {
- return normativesResolver.getAllNodeTypeNormatives();
- }
-
- @Override
- boolean save(Resource element) {
- if (e2eMalformedVfcs.contains(element.getUniqueId())) {
- replaceJcpVersionPropertyTypeToVersion(element);
- }
- return super.save(element);
- }
-
- private void replaceJcpVersionPropertyTypeToVersion(Resource element) {
- getJcpIntegerProperty(element).ifPresent(propertyDefinition -> {
- LOGGER.info("resource {} with id {}: found property jcp-version with type 'integer', changing type to 'version'", element.getName(), element.getUniqueId());
- propertyDefinition.setType(ToscaPropertyType.VERSION.getType());
- });
- }
-
- private Optional<PropertyDefinition> getJcpIntegerProperty(Resource element) {
- if (element.getProperties() == null) return Optional.empty();
- return element.getProperties().stream()
- .filter(prop -> prop.getName().equals(JCP_VERSION_PROPERTY))
- .filter(prop -> prop.getType().equals(ToscaPropertyType.INTEGER.getType()))
- .findAny();
-
- }
-
- @Override
- boolean doPostMigrateOperation(List<Resource> elements) {
- LOGGER.info("migrating node types versions");
- return versionMigration.buildComponentsVersionChain(elements);
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesResolver.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesResolver.java
deleted file mode 100644
index cc9e6ec972..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NormativesResolver.java
+++ /dev/null
@@ -1,101 +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.migration.v1707.jsonmodel;
-
-import fj.data.Either;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Queue;
-import java.util.stream.Collectors;
-
-public class NormativesResolver {
-
- @javax.annotation.Resource(name = "resource-operation")
- private IResourceOperation resourceOperation;
-
- /**
- *
- * @return list of all normatives sorted by neighboring order
- */
- public Either<List<Resource>, StorageOperationStatus> getAllNodeTypeNormatives() {
- Either<List<Resource>, StorageOperationStatus> rootNormatives = resourceOperation.getRootResources();
- return rootNormatives.either(this::getAllNormatives,
- Either::right);
-
- }
-
- private Either<List<Resource>, StorageOperationStatus> getAllNormatives(List<Resource> rootResources) {
- List<Resource> allNormatives = new ArrayList<>();
- for (Resource rootResource : rootResources) {
- Either<List<Resource>, StorageOperationStatus> normativesOfRoot = getAllNodeTypeNormatives(rootResource);
- if (normativesOfRoot.isRight()) {
- return Either.right(normativesOfRoot.right().value());
- }
- allNormatives.addAll(normativesOfRoot.left().value());
- }
- return Either.left(allNormatives);
- }
-
- private Either<List<Resource>, StorageOperationStatus> getAllNodeTypeNormatives(Resource root) {
- List<Resource> normativeResources = new ArrayList<>();
- Queue<Resource> resources = new ArrayDeque<>();
- resources.add(root);
- while (!resources.isEmpty()) {
- Resource currentResource = resources.poll();
- normativeResources.add(currentResource);
- Either<List<Resource>, StorageOperationStatus> allDerivedResources = getAllNonVFDerivedResources(currentResource);
- if (allDerivedResources.isRight()) {
- return Either.right(allDerivedResources.right().value());
- }
- List<Resource> derivedResources = allDerivedResources.left().value();
- replaceDerivedNameWithDerivedUniqueId(currentResource, derivedResources);
- resources.addAll(derivedResources);
- }
- return Either.left(normativeResources);
- }
-
- private void replaceDerivedNameWithDerivedUniqueId(Resource currentResource, List<Resource> derivedResources) {
- derivedResources.forEach(resource -> resource.setDerivedFrom(Collections.singletonList(currentResource.getUniqueId())));
- }
-
- private Either<List<Resource>, StorageOperationStatus> getAllNonVFDerivedResources(Resource resource) {
- Either<List<Resource>, StorageOperationStatus> childrenNodes = resourceOperation.getAllDerivedResources(resource);
- return childrenNodes.either(resourceList -> Either.left(filterNonVFResources(resourceList)),
- this::resolveEmptyListOrErrorStatus);
- }
-
- private List<Resource> filterNonVFResources(List<Resource> resources) {
- return resources.stream().filter(resource -> resource.getResourceType() != ResourceTypeEnum.VF).collect(Collectors.toList());
- }
-
- private Either<List<Resource>, StorageOperationStatus> resolveEmptyListOrErrorStatus(StorageOperationStatus storageOperationStatus) {
- return storageOperationStatus == StorageOperationStatus.NOT_FOUND ? Either.left(Collections.emptyList()) : Either.right(storageOperationStatus);
- }
-
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourceVersionMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourceVersionMigration.java
deleted file mode 100644
index aeb85a7d35..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourceVersionMigration.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.asdctool.impl.migration.v1707.jsonmodel;
-
-import fj.data.Either;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-
-import java.util.List;
-
-public class ResourceVersionMigration extends VersionMigration<Resource> {
-
- @javax.annotation.Resource(name = "resource-operation")
- private IResourceOperation resourceOperation;
-
- @Override
- NodeTypeEnum getNodeTypeEnum() {
- return NodeTypeEnum.Resource;
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourcesCategoriesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourcesCategoriesMigration.java
deleted file mode 100644
index f605d8c3fa..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ResourcesCategoriesMigration.java
+++ /dev/null
@@ -1,181 +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.migration.v1707.jsonmodel;
-
-import fj.data.Either;
-import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg;
-import org.openecomp.sdc.asdctool.impl.migration.Migration1707Task;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
-import org.openecomp.sdc.be.datatypes.category.CategoryDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-
-import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.CategoriesUtils.filterOldCategories;
-import static org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel.CategoriesUtils.filterOldSubCategories;
-
-
-public class ResourcesCategoriesMigration implements Migration1707Task {
-
- @Resource(name = "element-operation")
- private IElementOperation elementOperation;
-
- @Resource(name = "element-operation-migration")
- private IElementOperation elementOperationMigration;
-
- @Resource(name = "titan-dao")
- TitanDao titanDao;
-
- @Override
- public String description() {
- return "migrate resource categories";
- }
-
- @Override
- public boolean migrate() {
- return getCategoriesToMigrate().either(this::migrateCategories,
- errorStatus -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_RETRIEVE_CATEGORIES.getMessage(errorStatus.name())));
- }
-
- private Either<List<CategoryDefinition>, ActionStatus> getCategoriesToMigrate() {
- return elementOperation.getAllCategories(NodeTypeEnum.ResourceNewCategory, false);
- }
-
- private boolean migrateCategories(List<CategoryDefinition> categoryDefinitions) {
- List<CategoryDefinition> categoriesToMigrate = filterOldCategoriesAndSubCategories(categoryDefinitions);
- for (CategoryDefinition categoryDefinition : categoriesToMigrate) {
- boolean isMigrated = migrateCategoryIfNotExists(categoryDefinition);
- if (!isMigrated) {
- titanDao.rollback();
- return false;
- }
- titanDao.commit();
- }
- return true;
- }
-
-
- //since production was malformed we need to fixed it by removing wrong categories and sub categories
- private List<CategoryDefinition> filterOldCategoriesAndSubCategories(List<CategoryDefinition> categoryDefinitions) {
- Map<String, List<CategoryDefinition>> categoriesByNormalName = categoryDefinitions.stream().collect(Collectors.groupingBy(CategoryDataDefinition::getNormalizedName));
- List<CategoryDefinition> categoriesToMigrate = filterOldCategories(categoryDefinitions);
- for (CategoryDefinition categoryDefinition : categoriesToMigrate) {
- List<SubCategoryDefinition> newSubCategories = getAllDistinctSubCategories(categoriesByNormalName.get(categoryDefinition.getNormalizedName()));
- categoryDefinition.setSubcategories(newSubCategories);
- }
- return categoriesToMigrate;
- }
-
- private List<SubCategoryDefinition> getAllDistinctSubCategories (List<CategoryDefinition> categoriesDefinitions) {
- Map<String, List<SubCategoryDefinition>> subCategoriesByNormalName = categoriesDefinitions.stream()
- .filter(ct -> ct.getSubcategories()!=null)
- .flatMap(ct -> ct.getSubcategories().stream())
- .collect(Collectors.groupingBy(SubCategoryDefinition::getNormalizedName));
- return getDistinctSubCategories(subCategoriesByNormalName);
- }
-
- private List<SubCategoryDefinition> getDistinctSubCategories(Map<String, List<SubCategoryDefinition>> subCategoriesByNormalName) {
- List<SubCategoryDefinition> allSubCategories = new ArrayList<>();
- for (List<SubCategoryDefinition> subCategoryDefinitions : subCategoriesByNormalName.values()) {
- if (subCategoryDefinitions.size() == 1) {
- allSubCategories.addAll(subCategoryDefinitions);
- } else {
- allSubCategories.addAll(filterOldSubCategories(subCategoryDefinitions));
- }
- }
- return allSubCategories;
- }
-
- private boolean migrateCategoryIfNotExists(CategoryDefinition categoryDefinition) {
- return isExists(categoryDefinition).either(isExist -> isExist ? migrateSubCategories(categoryDefinition) : migrateCategoryAndSubCategories(categoryDefinition),
- error -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_RETRIEVE_CATEGORY.getMessage(categoryDefinition.getName(), error.name())));
- }
-
- private boolean migrateCategoryAndSubCategories(CategoryDefinition resourceCategory) {
- return elementOperationMigration.createCategory(resourceCategory, NodeTypeEnum.ResourceNewCategory)
- .either(createdCategory -> this.migrateSubCategories(resourceCategory),
- status -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_CREATE_CATEGORY.getMessage(resourceCategory.getName(), status.name())));
- }
-
- private boolean migrateSubCategories(CategoryDefinition categoryDefinition) {
- for (SubCategoryDefinition subCategory : categoryDefinition.getSubcategories()) {
- boolean isMigrated = migrateSubcategoryIfNotExists(categoryDefinition, subCategory);
- if (!isMigrated) {
- return false;
- }
- }
- return true;
- }
-
- private boolean migrateSubcategoryIfNotExists(CategoryDefinition parentCategory, SubCategoryDefinition subCategory) {
- return isExists(parentCategory, subCategory).either(isExists -> isExists || migrateSubCategory(parentCategory, subCategory),
- status -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_RETRIEVE_CATEGORY.getMessage(subCategory.getName(), status.name())));
- }
-
- private boolean migrateSubCategory(CategoryDefinition categoryDefinition, SubCategoryDefinition subCategory) {
- return elementOperationMigration.createSubCategory(categoryDefinition.getUniqueId(), subCategory, NodeTypeEnum.ResourceSubcategory)
- .either(createdSubCategory -> true,
- errorStatus -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_CREATE_SUB_CATEGORY.getMessage(subCategory.getName(), categoryDefinition.getName(), errorStatus.name())));
-
- }
-
- private Either<Boolean, ActionStatus> isExists(CategoryDefinition category) {
- Either<CategoryDefinition, ActionStatus> byId = getCategoryById(category);
- return byId.either(existingVal -> Either.left(true),
- this::getEitherNotExistOrErrorStatus);
- }
-
- private Either<Boolean, ActionStatus> isExists(CategoryDefinition parentCategory, SubCategoryDefinition subCategory) {
- return getSubCategoryById(parentCategory, subCategory).either(existingVal -> Either.left(true),
- this::getEitherNotExistOrErrorStatus);
- }
-
- private Either<Boolean, ActionStatus> getEitherNotExistOrErrorStatus(ActionStatus status) {
- return status == ActionStatus.COMPONENT_CATEGORY_NOT_FOUND ? Either.left(false) : Either.right(status);
- }
-
- private Either<CategoryDefinition, ActionStatus> getCategoryById(CategoryDefinition category) {
- return elementOperationMigration.getCategory(NodeTypeEnum.ResourceNewCategory, category.getUniqueId());
- }
-
- private Either<SubCategoryDefinition, ActionStatus> getSubCategoryById(CategoryDefinition parentCategory, SubCategoryDefinition subCategory) {
- String subCategoryUid = getExpectedSubCategoryId(parentCategory, subCategory);
- return elementOperationMigration.getSubCategory(NodeTypeEnum.ResourceSubcategory, subCategoryUid);
- }
-
- //since a sub category might belong to a different category in old graph its new graph id is different than its old graph id
- private String getExpectedSubCategoryId(CategoryDefinition parentCategory, SubCategoryDefinition subCategory) {
- String parentId = UniqueIdBuilder.buildCategoryUid(parentCategory.getNormalizedName(), NodeTypeEnum.ResourceNewCategory);
- return UniqueIdBuilder.buildSubCategoryUid(parentId, subCategory.getNormalizedName());
- }
-
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceCategoriesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceCategoriesMigration.java
deleted file mode 100644
index 857bcd9b43..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceCategoriesMigration.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.asdctool.impl.migration.v1707.jsonmodel;
-
-import fj.data.Either;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-
-import javax.annotation.Resource;
-import java.util.List;
-
-import static org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils.handleError;
-
-public class ServiceCategoriesMigration extends JsonModelMigration<CategoryDefinition> {
-
- @Resource(name = "element-operation")
- private IElementOperation elementOperation;
-
- @Resource(name = "element-operation-migration")
- private IElementOperation elementOperationMigration;
-
-
- @Override
- public String description() {
- return "migrate services categories";
- }
-
- @Override
- Either<List<CategoryDefinition>, ?> getElementsToMigrate() {
- return elementOperation.getAllCategories(NodeTypeEnum.ServiceNewCategory, false).left().map(CategoriesUtils::filterOldCategories);
- }
-
- @Override
- Either<CategoryDefinition, ?> getElementFromNewGraph(CategoryDefinition node) {
- String categoryUid = UniqueIdBuilder.buildCategoryUid(node.getNormalizedName(), NodeTypeEnum.ServiceNewCategory);//in malformed graph there are some categories with different id but same normalized name. so in new graph they same id
- return elementOperationMigration.getCategory(NodeTypeEnum.ServiceNewCategory, categoryUid);
- }
-
- @Override
- boolean save(CategoryDefinition graphNode) {
- return elementOperationMigration.createCategory(graphNode, NodeTypeEnum.ServiceNewCategory)
- .either(savedCategory -> true,
- err -> handleError(String.format("failed to save category %s. error: %s", graphNode.getName(), err.name())));
- }
-
- @Override
- ActionStatus getNotFoundErrorStatus() {
- return ActionStatus.COMPONENT_CATEGORY_NOT_FOUND;
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceVersionMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceVersionMigration.java
deleted file mode 100644
index 32ef06a220..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServiceVersionMigration.java
+++ /dev/null
@@ -1,43 +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.migration.v1707.jsonmodel;
-
-import fj.data.Either;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
-import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-
-import java.util.List;
-
-public class ServiceVersionMigration extends VersionMigration<Service> {
-
- @javax.annotation.Resource(name = "service-operation")
- private IServiceOperation serviceOperation;
-
- @Override
- NodeTypeEnum getNodeTypeEnum() {
- return NodeTypeEnum.Service;
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServicesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServicesMigration.java
deleted file mode 100644
index 040d220912..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ServicesMigration.java
+++ /dev/null
@@ -1,180 +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.migration.v1707.jsonmodel;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import javax.annotation.Resource;
-
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
-import org.openecomp.sdc.be.model.operations.migration.MigrationMalformedDataLogger;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import fj.data.Either;
-
-public class ServicesMigration extends ComponentMigration<Service> {
-
- private static final String DEFAULT_CONFORMANCE_LEVEL = "0.0";
- private static Logger LOGGER = LoggerFactory.getLogger(ServicesMigration.class);
-
- @Resource(name = "service-operation")
- private IServiceOperation serviceOperation;
-
- @Resource(name = "service-version-migration")
- private VersionMigration<Service> versionMigration;
-
- @Override
- public String description() {
- return "migrate services";
- }
-
- @Override
- Either<List<Service>, ?> getElementsToMigrate() {
- return serviceOperation.getAll();
- }
-
- @Override
- boolean save(Service element) {
- MigrationMalformedDataLogger.logIfServiceUsingMalformedVfs(element);
- filterOutDuplicatePropsAndAttrs(element);
- element.setConformanceLevel(DEFAULT_CONFORMANCE_LEVEL);
- requirementsCapabilitiesMigrationService.overrideInstanceCapabilitiesRequirements(element);
- return super.save(element);
- }
-
- @Override
- boolean doPostSaveOperation(Service element) {
- return element.getComponentInstances() == null ||
- (requirementsCapabilitiesMigrationService.associateFulfilledRequirements(element, NodeTypeEnum.Service) &&
- requirementsCapabilitiesMigrationService.associateFulfilledCapabilities(element, NodeTypeEnum.Service));
- }
-
- @Override
- boolean doPostMigrateOperation(List<Service> elements) {
- LOGGER.info("migrating services versions");
- return versionMigration.buildComponentsVersionChain(elements);
- }
-
- @Override
- void doPreMigrationOperation(List<Service> elements) {
- super.doPreMigrationOperation(elements);
- setMissingTemplateInfo(elements);
- }
-
- private void filterOutDuplicatePropsAndAttrs(Service element) {
- if (element.getComponentInstancesProperties() != null) {
- removeDuplicatedNameProperties(element);
- }
- if (element.getComponentInstancesAttributes() != null) {
- removeDuplicatedNameAttributes(element);
- }
- }
-
- private void removeDuplicatedNameProperties(Service service) {
- Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = service.getComponentInstancesProperties();
- componentInstancesProperties.forEach((uid, properties) -> {
- componentInstancesProperties.put(uid, getUniquedNamePropertyList(service, properties));
- });
- }
-
- private List<ComponentInstanceProperty> getUniquedNamePropertyList(Service service, List<ComponentInstanceProperty> properties) {
- if (properties == null) {
- return null;
- }
- List<ComponentInstanceProperty> uniqueNameProperties = new ArrayList<>();
- Map<String, List<ComponentInstanceProperty>> collect = properties.stream().collect(Collectors.groupingBy(ComponentInstanceProperty::getName));
- collect.forEach((name, duplicatedProperties) -> {
- logServiceDuplicateProperties(service, name, duplicatedProperties);
- uniqueNameProperties.add(duplicatedProperties.get(0));
- });
- return uniqueNameProperties;
- }
-
- private void logServiceDuplicateProperties(Service service, String name, List<ComponentInstanceProperty> duplicatedProperties) {
- if (duplicatedProperties.size() > 1) {
- LOGGER.debug("service {} with id {} has instance {} with duplicate property {}", service.getName(), service.getUniqueId(), duplicatedProperties.get(0).getUniqueId(), name);
- }
- }
-
- private void removeDuplicatedNameAttributes(Service service) {
- Map<String, List<ComponentInstanceProperty>> componentInstancesAttributes = service.getComponentInstancesAttributes();
- componentInstancesAttributes.forEach((uid, attributes) -> {
- componentInstancesAttributes.put(uid, getUniquedNameAttributeList(service, attributes));
- });
- }
-
- private List<ComponentInstanceProperty> getUniquedNameAttributeList(Service service, List<ComponentInstanceProperty> attributes) {
- if (attributes == null) {
- return null;
- }
- List<ComponentInstanceProperty> uniqueNameAttributes = new ArrayList<>();
- Map<String, List<ComponentInstanceProperty>> collect = attributes.stream().collect(Collectors.groupingBy(ComponentInstanceProperty::getName));
- collect.forEach((name, duplicatedAttributess) -> {
- logServiceMalformedAttributes(service, name, duplicatedAttributess);
- uniqueNameAttributes.add(duplicatedAttributess.get(0));
- });
- return uniqueNameAttributes;
- }
-
- private void logServiceMalformedAttributes(Service service, String name, List<ComponentInstanceProperty> duplicatedAttributess) {
- if (duplicatedAttributess.size() > 1) {
- MigrationMalformedDataLogger.logMalformedDataMsg(String.format("service %s with id %s has instance %s with duplicate attribute %s",
- service.getName(), service.getUniqueId(), duplicatedAttributess.get(0).getUniqueId(), name));
- }
- }
-
- // private void filterOutVFInstanceAttrs(Service element, List<String> vfInstancesIds) {
-// Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = element.getComponentInstancesAttributes();
-// if (componentInstancesAttributes != null) {
-// element.setComponentInstancesAttributes(filterOutVFInstanceAttributes(componentInstancesAttributes, vfInstancesIds));
-// }
-// }
-//
-// private void filterOutVFInstacnecProps(Service element, List<String> vfInstancesIds) {
-// Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = element.getComponentInstancesProperties();
-// if (componentInstancesProperties != null) {
-// element.setComponentInstancesProperties(filterOutVFInstanceProperties(componentInstancesProperties, vfInstancesIds));
-// }
-// }
-//
-// private Map<String, List<ComponentInstanceProperty>> filterOutVFInstanceProperties(Map<String, List<ComponentInstanceProperty>> instances, List<String> vfInstanceIds) {
-// return instances.entrySet()
-// .stream()
-// .filter(entry -> !vfInstanceIds.contains(entry.getKey()))
-// .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
-// }
-//
-// private Map<String, List<ComponentInstanceAttribute>> filterOutVFInstanceAttributes(Map<String, List<ComponentInstanceAttribute>> instances, List<String> vfInstanceIds) {
-// return instances.entrySet()
-// .stream()
-// .filter(entry -> !vfInstanceIds.contains(entry.getKey()))
-// .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
-// }
-
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UserStatesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UserStatesMigration.java
deleted file mode 100644
index 3f62273931..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UserStatesMigration.java
+++ /dev/null
@@ -1,187 +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.migration.v1707.jsonmodel;
-
-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.apache.tinkerpop.gremlin.structure.Property;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg;
-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.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.resources.data.UserData;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Collectors;
-
-import static fj.data.List.list;
-import static org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils.handleError;
-
-public class UserStatesMigration extends JsonModelMigration<Edge> {
-
- private static final String MIGRATING_USER_ID = "jh0003";
- private static final int OUT_VERTEX_INDEX = 0;
- private static final int IN_VERTEX_INDEX = 1;
- private static Logger LOGGER = LoggerFactory.getLogger(UserStatesMigration.class);
-
- @Resource(name = "titan-generic-dao")
- private TitanGenericDao genericDao;
-
- @Resource(name = "titan-generic-dao-migration")
- private TitanGenericDao genericDaoMigration;
-
- @Override
- public String description() {
- return "migrate user states";
- }
-
-
- @Override
- public boolean migrate() {
-// return removeMigratingUserStates() && super.migrate();
- return super.migrate();
- }
-
- @Override
- Either<List<Edge>, TitanOperationStatus> getElementsToMigrate() {
- LOGGER.debug("fetching user states edges from old graph");
- return genericDao.getAll(NodeTypeEnum.User, UserData.class)
- .left().bind(this::getEdgesForUsers);
- }
-
- @Override
- Either<Edge, TitanOperationStatus> getElementFromNewGraph(Edge edge) {
- LOGGER.debug("finding user state edge in new graph");
- Vertex outVertex = edge.outVertex();
- String outVertexUIDKey = getVertexUniqueId(outVertex);
- String outVertexUIDValue = outVertex.property(outVertexUIDKey).value().toString();
-
- Vertex inVertex = edge.inVertex();
- String inVertexUIDKey = getVertexUniqueId(inVertex);
- String inVertexUIDValue = inVertex.property(inVertexUIDKey).value().toString();
-
- return genericDaoMigration.getEdgeByVerticies(outVertexUIDKey, outVertexUIDValue, inVertexUIDKey, inVertexUIDValue, edge.label());
- }
-
- @Override
- boolean save(Edge userState) {
- Either<InOutVertices, TitanOperationStatus> titanVertices = findEdgeInOutVerticesInNewGraph(userState);
- return titanVertices.either(inOutVertices -> saveUserState(inOutVertices, userState),
- err -> handleError(String.format("could not find user edge %s in vertx. error: %s", userState.label(), err.name())));
- }
-
- private boolean saveUserState(InOutVertices inOutVertices, Edge userState) {
- return genericDaoMigration.copyEdge(inOutVertices.getOutVertex(), inOutVertices.getInVertex(), userState)
- .either(edge -> true,
- err -> handleError(String.format("failed to save user state edge %s. reason: %s", userState.label(), err.name())));
- }
-
- @Override
- TitanOperationStatus getNotFoundErrorStatus() {
- return TitanOperationStatus.NOT_FOUND;
- }
-
-// private boolean removeMigratingUserStates() {
-// Either<UserData, TitanOperationStatus> migratingUser = genericDaoMigration.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), MIGRATING_USER_ID, UserData.class);
-// return migratingUser.either(user -> deleteAllEdges(user, Direction.OUT),
-// errorStatus -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_RETRIEVE_MIGRATION_USER.getMessage(MIGRATING_USER_ID, errorStatus.name())));
-// }
-
- private Either<List<Edge>, TitanOperationStatus> getEdgesForUsers(List<UserData> users) {
- List<Edge> edges = new ArrayList<>();
- for (UserData user : users) {
- Either<List<Edge>, TitanOperationStatus> edgesForNode = genericDao.getEdgesForNode(user, Direction.OUT);
- if (edgesForNode.isRight()) {
- TitanOperationStatus errorStatus = edgesForNode.right().value();
- LOGGER.error(MigrationMsg.FAILED_TO_RETRIEVE_USER_STATES.getMessage(user.getEmail(), errorStatus.name()));
- return Either.right(errorStatus);
- }
- edges.addAll(edgesForNode.left().value());
- }
- return Either.left(ignoreProductEdges(edges));
- }
-
- private List<Edge> ignoreProductEdges(List<Edge> edges) {
- return edges.stream().filter(edge -> !isInEdgeOfProductType(edge.inVertex())).collect(Collectors.toList());
- }
-
- private boolean isInEdgeOfProductType(Vertex inVertex) {
- Property<Object> nodeLabelProperty = inVertex.property(GraphPropertiesDictionary.LABEL.getProperty());
- return nodeLabelProperty != null && nodeLabelProperty.value().equals(NodeTypeEnum.Product.getName());
- }
-
- private String getVertexUniqueId(Vertex vertex) {
- String nodeLabel = vertex.property(GraphPropertiesDictionary.LABEL.getProperty()).value().toString();
- return UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(nodeLabel));
- }
-
- private Either<InOutVertices, TitanOperationStatus> findEdgeInOutVerticesInNewGraph(Edge userEdge) {
- Either<TitanVertex, TitanOperationStatus> outVertex = getMigratedVertexByOldVertex(userEdge.outVertex());
- Either<TitanVertex, TitanOperationStatus> inVertex = getMigratedVertexByOldVertex(userEdge.inVertex());
- return Either.sequenceLeft(list(outVertex, inVertex)).left().map(InOutVertices::new);
- }
-
- private Either<TitanVertex, TitanOperationStatus> getMigratedVertexByOldVertex(Vertex vertex) {
- String vertexUniqueId = getVertexUniqueId(vertex);
- LOGGER.debug(String.format("fetching vertex %s from new graph", vertexUniqueId));
- return genericDaoMigration.getVertexByProperty(vertexUniqueId, vertex.property(vertexUniqueId).value())
- .right().map(err -> handleError(err, String.format("could not find vertex %s in new graph.", vertexUniqueId))) ;
- }
-
-// private boolean deleteAllEdges(UserData userData, Direction direction) {
-// Either<List<Edge>, TitanOperationStatus> edgesForNode = genericDaoMigration.getEdgesForNode(userData, direction);
-// if (edgesForNode.isRight()) {
-// LOGGER.error(MigrationMsg.FAILED_TO_RETRIEVE_MIGRATION_USER_STATES.getMessage(MIGRATING_USER_ID, edgesForNode.right().value().name()));
-// return false;
-// }
-// edgesForNode.left().value().forEach(Edge::remove);
-// return true;
-// }
-
- private class InOutVertices {
- private TitanVertex outVertex;
- private TitanVertex inVertex;
-
- InOutVertices(fj.data.List<TitanVertex> inOutVertices) {
- outVertex = inOutVertices.index(OUT_VERTEX_INDEX);
- inVertex = inOutVertices.index(IN_VERTEX_INDEX);
- }
-
- TitanVertex getOutVertex() {
- return outVertex;
- }
-
- TitanVertex getInVertex() {
- return inVertex;
- }
-
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UsersMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UsersMigration.java
deleted file mode 100644
index 6e0a8a9247..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/UsersMigration.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.asdctool.impl.migration.v1707.jsonmodel;
-
-import fj.data.Either;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.annotation.Resource;
-import java.util.List;
-
-import static org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils.handleError;
-
-public class UsersMigration extends JsonModelMigration<User> {
-
- private static Logger LOGGER = LoggerFactory.getLogger(UsersMigration.class);
-
- @Resource(name = "user-operation")
- IUserAdminOperation userAdminOperation;
-
- @Resource(name = "user-operation-migration")
- IUserAdminOperation userAdminOperationMigration;
-
-
- @Override
- Either<List<User>, ActionStatus> getElementsToMigrate() {
- LOGGER.debug("fetching users to migrate from old graph");
- return userAdminOperation.getAllUsers();
- }
-
- @Override
- Either<User, ActionStatus> getElementFromNewGraph(User user) {
- LOGGER.debug(String.format("trying to load user %s from new graph", user.getUserId()));
- return user.getStatus().equals(UserStatusEnum.ACTIVE) ? userAdminOperationMigration.getUserData(user.getUserId(), false) :
- userAdminOperationMigration.getInactiveUserData(user.getUserId());
- }
-
- @Override
- boolean save(User user) {
- LOGGER.debug(String.format("trying to save user %s to new graph", user.getUserId()));
- return userAdminOperationMigration.saveUserData(user)
- .either(savedUser -> true,
- err -> handleError(String.format("failed when saving user %s. error %s", user.getUserId(), err.name())));
- }
-
- @Override
- public ActionStatus getNotFoundErrorStatus() {
- return ActionStatus.USER_NOT_FOUND;
- }
-
- @Override
- public String description() {
- return "migrate users";
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VFResourcesMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VFResourcesMigration.java
deleted file mode 100644
index 82d22addf3..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VFResourcesMigration.java
+++ /dev/null
@@ -1,79 +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.migration.v1707.jsonmodel;
-
-import java.util.List;
-
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import fj.data.Either;
-
-public class VFResourcesMigration extends ComponentMigration<Resource> {
-
- private static Logger LOGGER = LoggerFactory.getLogger(VFResourcesMigration.class);
-
- @javax.annotation.Resource(name = "resource-operation")
- private IResourceOperation resourceOperation;
-
- @javax.annotation.Resource(name = "resource-version-migration")
- private VersionMigration<Resource> versionMigration;
-
- @Override
- public String description() {
- return "migrate VFs";
- }
-
- @Override
- Either<List<Resource>, ?> getElementsToMigrate() {
- return resourceOperation.getVFResources();
- }
-
- @Override
- boolean save(Resource element) {
- requirementsCapabilitiesMigrationService.overrideInstanceCapabilitiesRequirements(element);
- return super.save(element);
- }
-
- @Override
- boolean doPostSaveOperation(Resource element) {
- return element.getComponentInstances() == null ||
- (requirementsCapabilitiesMigrationService.associateFulfilledRequirements(element, NodeTypeEnum.Resource) &&
- requirementsCapabilitiesMigrationService.associateFulfilledCapabilities(element, NodeTypeEnum.Resource));
- }
-
- @Override
- boolean doPostMigrateOperation(List<Resource> elements) {
- LOGGER.info("migrating VFs versions");
- return versionMigration.buildComponentsVersionChain(elements);
- }
-
- @Override
- void doPreMigrationOperation(List<Resource> elements) {
- super.doPreMigrationOperation(elements);
- setMissingTemplateInfo(elements);
- }
-
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VersionMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VersionMigration.java
deleted file mode 100644
index 514760fba2..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/VersionMigration.java
+++ /dev/null
@@ -1,118 +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.migration.v1707.jsonmodel;
-
-import fj.data.Either;
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.openecomp.sdc.asdctool.impl.migration.MigrationMsg;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils;
-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.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.annotation.Resource;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-public abstract class VersionMigration<T extends Component> {
-
- private static Logger LOGGER = LoggerFactory.getLogger(VersionMigration.class);
-
- @Resource(name = "titan-generic-dao-migration")
- private TitanGenericDao titanGenericDaoMigration;
-
- @Resource(name = "titan-dao")
- private TitanDao titanDao;
-
- public boolean buildComponentsVersionChain(List<T> components) {
- Map<String, List<T>> componentsByInvariant = components.stream().filter(c -> c.getInvariantUUID() != null).collect(Collectors.groupingBy(Component::getInvariantUUID));
- for (List<T> componentsList : componentsByInvariant.values()) {
- boolean versionChainBuilt = buildVersionChainForInvariant(componentsList);
- if (!versionChainBuilt) {
- titanDao.rollback();
- return false;
- }
- titanDao.commit();
- }
- return true;
- }
-
- private boolean buildVersionChainForInvariant(List<T> components) {
- sortComponentsByVersion(components);
- for (int i = 0; i < components.size() -1; i++) {
- String lowerVersionUid = components.get(i).getUniqueId();
- String higherVersionUid = components.get(i + 1).getUniqueId();
- boolean versionCreated = createVersionRelationIfNotExist(lowerVersionUid, higherVersionUid);
- if (!versionCreated) {
- return false;
- }
- }
- return true;
- }
-
- private void sortComponentsByVersion(List<T> components) {
- Collections.sort(components, (o1, o2) -> Double.valueOf(o1.getVersion()).compareTo(Double.valueOf(o2.getVersion())));
- }
-
- private boolean createVersionRelationIfNotExist(String fromUid, String toUid) {
- Either<Boolean, TitanOperationStatus> isVersionExists = isVersionExists(fromUid, toUid);
- return isVersionExists.either(versionExists -> versionExists || createVersionRelation(fromUid, toUid),
- errorStatus -> MigrationUtils.handleError(MigrationMsg.FAILED_TO_RETRIEVE_VERSION_RELATION.getMessage(fromUid, toUid, isVersionExists.right().value().name())));
- }
-
- private boolean createVersionRelation(String fromUid, String toUid) {
- LOGGER.debug(String.format("creating version edge between vertex %s and vertex %s", fromUid, toUid));
- Either<GraphVertex, TitanOperationStatus> fromVertex = titanDao.getVertexById(fromUid);
- Either<GraphVertex, TitanOperationStatus> toVertex = titanDao.getVertexById(toUid);
- if (toVertex.isLeft() && fromVertex.isLeft()) {
- TitanOperationStatus versionCreated = titanDao.createEdge(fromVertex.left().value(), toVertex.left().value(), EdgeLabelEnum.VERSION, new HashMap<>());
- return versionCreated == TitanOperationStatus.OK;
- }
- return MigrationUtils.handleError(String.format("could not create version edge between vertex %s and vertex %s.", fromUid, toUid));
- }
-
- private Either<Boolean, TitanOperationStatus> isVersionExists(String fromUid, String toUid) {
- LOGGER.debug(String.format("checking if version edge between vertex %s and vertex %s already exist", fromUid, toUid));
- String uidKey = UniqueIdBuilder.getKeyByNodeType(getNodeTypeEnum());
- Either<Edge, TitanOperationStatus> edgeByVertices = titanGenericDaoMigration.getEdgeByVerticies(uidKey, fromUid, uidKey, toUid, EdgeLabelEnum.VERSION.name());
- if (isNotFoundStatus(edgeByVertices)) {
- return Either.left(false);
- }
- return edgeByVertices.bimap(foundEdge -> true,
- error -> error);
- }
-
- private boolean isNotFoundStatus(Either<Edge, TitanOperationStatus> edgeByVertices) {
- return edgeByVertices.isRight() && edgeByVertices.right().value() == TitanOperationStatus.NOT_FOUND;
- }
-
- abstract NodeTypeEnum getNodeTypeEnum();
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilitiesMigrationService.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilitiesMigrationService.java
deleted file mode 100644
index 23b1afec93..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilitiesMigrationService.java
+++ /dev/null
@@ -1,104 +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.migration.v1707.jsonmodel.relations;
-
-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.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.CapabilityDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.operations.api.ICapabilityOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
-import org.openecomp.sdc.be.resources.data.CapabilityData;
-
-import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-public class FulfilledCapabilitiesMigrationService extends FulfilledCapabilityRequirementMigrationService<CapabilityDefinition, CapabilityData> {
-
- @Resource(name = "capability-operation")
- private ICapabilityOperation capabilityOperation;
-
- @Resource(name = "component-instance-operation")
- private ComponentInstanceOperation componentInstanceOperation;
-
- @Override
- Either<CapabilityDefinition, StorageOperationStatus> getToscaDefinition(CapabilityData data) {
- return capabilityOperation.getCapability(data.getUniqueId());
- }
-
- @Override
- void setPath(CapabilityDefinition def, List<String> path) {
- def.setPath(path);
- }
-
- @Override
- String getType(CapabilityDefinition def) {
- return def.getType();
- }
-
- @Override
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getFulfilledCapReqs(ComponentInstance instance, NodeTypeEnum nodeTypeEnum) {
- return componentInstanceOperation.getFulfilledCapabilities(instance, nodeTypeEnum);
- }
-
- @Override
- ListDataDefinition convertToDefinitionListObject(List<CapabilityDefinition> capReqDefList) {
- List<CapabilityDataDefinition> capabilityDataDefinitions = new ArrayList<>();
- capabilityDataDefinitions.addAll(capReqDefList);
- return new ListCapabilityDataDefinition(capabilityDataDefinitions);
- }
-
- @Override
- MapDataDefinition convertToDefinitionMapObject(Map<String, ListDataDefinition> reqCapForInstance) {
- Map<String, ListCapabilityDataDefinition> capabilitiesList = castDataDefinitionListToCapabilityList(reqCapForInstance);
- return new MapListCapabiltyDataDefinition(capabilitiesList);
- }
-
- @Override
- Either<GraphVertex, TitanOperationStatus> getAssociatedDefinitions(GraphVertex component) {
- return titanDao.getChildVertex(component, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, JsonParseFlagEnum.NoParse);
- }
-
- @Override
- Either<GraphVertex, StorageOperationStatus> associateToGraph(GraphVertex graphVertex, Map<String, MapDataDefinition> defsByInstance) {
- return topologyTemplateOperation.assosiateElementToData(graphVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, defsByInstance);
- }
-
- private Map<String, ListCapabilityDataDefinition> castDataDefinitionListToCapabilityList(Map<String, ListDataDefinition> reqCapForInstance) {
- return reqCapForInstance.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> (ListCapabilityDataDefinition) entry.getValue()));
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilityRequirementMigrationService.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilityRequirementMigrationService.java
deleted file mode 100644
index 33b5574408..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledCapabilityRequirementMigrationService.java
+++ /dev/null
@@ -1,184 +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.migration.v1707.jsonmodel.relations;
-
-import fj.Function;
-import fj.data.Either;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.asdctool.impl.migration.MigrationException;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
-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.ListDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.annotation.Resource;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import static org.openecomp.sdc.asdctool.impl.migration.MigrationMsg.*;
-import static org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationUtils.willThrowException;
-
-public abstract class FulfilledCapabilityRequirementMigrationService<T extends ToscaDataDefinition, S extends GraphNode> {
-
- private static Logger LOGGER = LoggerFactory.getLogger(FulfilledCapabilityRequirementMigrationService.class);
-
- @Resource(name = "topology-template-operation")
- TopologyTemplateOperation topologyTemplateOperation;
-
- @Resource(name = "tosca-path-calculator")
- private ToscaDefinitionPathCalculator toscaDefinitionPathCalculator;
-
- @Resource(name = "titan-dao")
- TitanDao titanDao;
-
- public boolean associateToscaDefinitions(Component component, NodeTypeEnum componentType) {
- try {
- return isDefinitionsAlreadyAssociated(component) || doAssociateToscaDefinitions(component, componentType);
- } catch (MigrationException e) {
- LOGGER.error(e.getMessage(), e);
- return false;
- }
- }
-
- private boolean isDefinitionsAlreadyAssociated(Component component) {
- GraphVertex componentVertex = titanDao.getVertexById(component.getUniqueId()).left().on((err) -> willThrowException(FAILED_TO_RETRIEVE_VERTEX.getMessage(component.getName(), err.name())));
- return this.getAssociatedDefinitions(componentVertex)
- .either(vertex -> true,
- errorStatus -> notFoundStatusOrFail(component, errorStatus));
-
- }
-
- private boolean notFoundStatusOrFail(Component component, TitanOperationStatus error) {
- if (error.equals(TitanOperationStatus.NOT_FOUND)) {
- return false;
- }
- throw new MigrationException(FAILED_TO_RETRIEVE_CAP_REQ_VERTEX.getMessage(component.getName(), error.name()));
- }
-
- private boolean doAssociateToscaDefinitions(Component component, NodeTypeEnum componentType) {
- try {
- Map<String, MapDataDefinition> toscaDefByInstance = groupToscaDefinitionByInstance(component, componentType);
- return toscaDefByInstance.isEmpty() || updateOnGraph(component, toscaDefByInstance);
- } catch (MigrationException e) {
- LOGGER.error(e.getMessage(), e);
- return false;
- }
- }
-
- private Map<String, MapDataDefinition> groupToscaDefinitionByInstance(Component component, NodeTypeEnum componentType) {
- Map<String, MapDataDefinition> toscaDefByInstance = new HashMap<>();
- for (ComponentInstance componentInstance : component.getComponentInstances()) {
- List<ImmutablePair<S, GraphEdge>> fulfilledCapReq = getFulfilledCapReqs(componentType, componentInstance);
- if (fulfilledCapReq.isEmpty()) {
- continue;
- }
- toscaDefByInstance.put(componentInstance.getUniqueId(), getReqCapToscaDefs(fulfilledCapReq, componentInstance));
- }
- return toscaDefByInstance;
- }
-
- private MapDataDefinition getReqCapToscaDefs(List<ImmutablePair<S, GraphEdge>> capReqsData, ComponentInstance componentInstance) {
- Map<String, List<T>> capReqDefinitions = getCapReqDefinitions(componentInstance, capReqsData);
- return convertToMapDefinition(capReqDefinitions);
- }
-
- private List<ImmutablePair<S, GraphEdge>> getFulfilledCapReqs(NodeTypeEnum componentType, ComponentInstance componentInstance) {
- return getFulfilledCapReqs(componentInstance, componentType)
- .either(Function.identity(),
- error -> emptyListOrFail(error, componentInstance.getName()));
- }
-
- private List<ImmutablePair<S, GraphEdge>> emptyListOrFail(TitanOperationStatus error, String instanceName) {
- if (error.equals(TitanOperationStatus.NOT_FOUND)) {
- return Collections.emptyList();
- }
- String errorMsg = FAILED_TO_RETRIEVE_REQ_CAP.getMessage(instanceName, error.name());
- throw new MigrationException(errorMsg);
- }
-
- private Map<String, List<T>> getCapReqDefinitions(ComponentInstance componentInstance, List<ImmutablePair<S, GraphEdge>> capReqDataList) {
- return capReqDataList.stream()
- .map(capReqData -> convertToToscaDef(componentInstance, capReqData))
- .collect(Collectors.groupingBy(this::getType));
- }
-
- private T convertToToscaDef(ComponentInstance componentInstance, ImmutablePair<S, GraphEdge> data) {
- T def = getReqCapDataDefinition(data);
- List<String> definitionPath = toscaDefinitionPathCalculator.calculateToscaDefinitionPath(componentInstance, data.getRight());
- setPath(def, definitionPath);
- return def;
- }
-
- private T getReqCapDataDefinition(ImmutablePair<S, GraphEdge> data) {
- S capReqData = data.getLeft();
- return getToscaDefinition(capReqData).left().on(err -> willThrowException(FAILED_TO_RETRIEVE_TOSCA_DEF.getMessage(capReqData.getUniqueId().toString(), err.toString())));
- }
-
- private boolean updateOnGraph(Component component, Map<String, MapDataDefinition> defsByInstance) {
- GraphVertex graphVertex = getComponentGraphVertex(component);
- Either<GraphVertex, StorageOperationStatus> associatedVertex = associateToGraph(graphVertex, defsByInstance);
- return associatedVertex.either(vertex -> true, err -> MigrationUtils.handleError(FAILED_TO_ASSOCIATE_CAP_REQ.getMessage(component.getName(), err.name())));
- }
-
- private GraphVertex getComponentGraphVertex(Component component) {
- return titanDao.getVertexById(component.getUniqueId())
- .left().on(error -> willThrowException(FAILED_TO_RETRIEVE_VERTEX.getMessage(component.getUniqueId(), error.name())));
- }
-
- private MapDataDefinition convertToMapDefinition(Map<String, List<T>> toscaDefs) {
- Map<String, ListDataDefinition> defsListByType = toscaDefs.entrySet().stream()
- .collect(Collectors.toMap(Map.Entry::getKey, entry -> convertToDefinitionListObject(entry.getValue())));
- return convertToDefinitionMapObject(defsListByType);
- }
-
- abstract Either<T, ?> getToscaDefinition(S data);
-
- abstract void setPath(T def, List<String> path);
-
- abstract String getType(T def);
-
- abstract Either<List<ImmutablePair<S, GraphEdge>>, TitanOperationStatus> getFulfilledCapReqs(ComponentInstance instance, NodeTypeEnum nodeTypeEnum);
-
- abstract ListDataDefinition convertToDefinitionListObject(List<T> capReqDefList);
-
- abstract MapDataDefinition convertToDefinitionMapObject(Map<String, ListDataDefinition> reqCapForInstance);
-
- abstract Either<GraphVertex, TitanOperationStatus> getAssociatedDefinitions(GraphVertex component);
-
- abstract Either<GraphVertex, StorageOperationStatus> associateToGraph(GraphVertex graphVertex, Map<String, MapDataDefinition> defsByInstance);
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledRequirementsMigrationService.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledRequirementsMigrationService.java
deleted file mode 100644
index 2b720af751..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/FulfilledRequirementsMigrationService.java
+++ /dev/null
@@ -1,104 +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.migration.v1707.jsonmodel.relations;
-
-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.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.ListDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
-import org.openecomp.sdc.be.model.operations.api.IRequirementOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.resources.data.RequirementData;
-
-import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-public class FulfilledRequirementsMigrationService extends FulfilledCapabilityRequirementMigrationService<RequirementDefinition, RequirementData> {
-
- @Resource(name = "requirement-operation")
- IRequirementOperation requirementOperation;
-
- @Resource(name = "component-instance-operation")
- IComponentInstanceOperation componentInstanceOperation;
-
- @Override
- Either<RequirementDefinition, TitanOperationStatus> getToscaDefinition(RequirementData data) {
- return requirementOperation.getRequirement(data.getUniqueId());
- }
-
- @Override
- void setPath(RequirementDefinition def, List<String> path) {
- def.setPath(path);
- }
-
- @Override
- String getType(RequirementDefinition def) {
- return def.getCapability();
- }
-
- @Override
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getFulfilledCapReqs(ComponentInstance instance, NodeTypeEnum nodeTypeEnum) {
- return componentInstanceOperation.getFulfilledRequirements(instance, nodeTypeEnum);
- }
-
- @Override
- ListDataDefinition convertToDefinitionListObject(List<RequirementDefinition> capReqDefList) {
- List<RequirementDataDefinition> requirementDataDefinitions = new ArrayList<>();
- requirementDataDefinitions.addAll(capReqDefList);
- return new ListRequirementDataDefinition(requirementDataDefinitions);
- }
-
- @Override
- MapDataDefinition convertToDefinitionMapObject(Map<String, ListDataDefinition> reqCapForInstance) {
- Map<String, ListRequirementDataDefinition> reqDefList = castDefinitionListToRequirementList(reqCapForInstance);
- return new MapListRequirementDataDefinition(reqDefList);
- }
-
- @Override
- Either<GraphVertex, TitanOperationStatus> getAssociatedDefinitions(GraphVertex component) {
- return titanDao.getChildVertex(component, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, JsonParseFlagEnum.NoParse);
- }
-
- @Override
- Either<GraphVertex, StorageOperationStatus> associateToGraph(GraphVertex graphVertex, Map<String, MapDataDefinition> defsByInstance) {
- return topologyTemplateOperation.assosiateElementToData(graphVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, defsByInstance);
- }
-
- private Map<String, ListRequirementDataDefinition> castDefinitionListToRequirementList(Map<String, ListDataDefinition> reqCapForInstance) {
- return reqCapForInstance.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> (ListRequirementDataDefinition) entry.getValue()));
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/RequirementsCapabilitiesMigrationService.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/RequirementsCapabilitiesMigrationService.java
deleted file mode 100644
index e468dd2fc5..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/relations/RequirementsCapabilitiesMigrationService.java
+++ /dev/null
@@ -1,111 +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.migration.v1707.jsonmodel.relations;
-
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-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.RequirementDefinition;
-
-import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-public class RequirementsCapabilitiesMigrationService<T extends Component> {
-
- @Resource(name = "fulfilled-capabilities-mig-service")
- FulfilledCapabilitiesMigrationService fulfilledCapabilityUpdate;
-
- @Resource(name = "fulfilled-requirements-mig-service")
- FulfilledRequirementsMigrationService fulfilledRequirementUpdate;
-
- public boolean associateFulfilledCapabilities(T component, NodeTypeEnum nodeType) {
- return fulfilledCapabilityUpdate.associateToscaDefinitions(component, nodeType);
- }
-
- public boolean associateFulfilledRequirements(T component, NodeTypeEnum nodeType) {
- return fulfilledRequirementUpdate.associateToscaDefinitions(component, nodeType);
- }
-
- public void overrideInstanceCapabilitiesRequirements(T element) {
- if (element.getComponentInstances() != null) {
- clearInstancesCapabilitiesRequirements(element);
- setInstancesRequirementsFromComponent(element);
- setInstancesCapabilitiesFromComponent(element);
- }
- }
-
- private void clearInstancesCapabilitiesRequirements(T element) {
- element.getComponentInstances().forEach(componentInstance -> {
- if (componentInstance.getCapabilities() != null) {
- componentInstance.getCapabilities().clear();
- }
- if (componentInstance.getRequirements() != null) {
- componentInstance.getRequirements().clear();
- }
- });
- }
-
- private void setInstancesCapabilitiesFromComponent(T element) {
- if (element.getCapabilities() != null) {
- Map<String, ComponentInstance> instancesById = groupInstancesById(element);
- element.getCapabilities().forEach((type, definitions) -> { setCapabilitiesOnInstance(instancesById, type, definitions);});
- }
- }
-
- private void setInstancesRequirementsFromComponent(T element) {
- if (element.getRequirements() != null) {
- Map<String, ComponentInstance> instancesById = groupInstancesById(element);
- element.getRequirements().forEach((type, requirements) -> { setRequirementsOnInstance(instancesById, type, requirements);});
- }
- }
-
- private void setCapabilitiesOnInstance(Map<String, ComponentInstance> instances, String capabilityType, List<CapabilityDefinition> definitions) {
- Map<String, List<CapabilityDefinition>> capByInstance = definitions.stream().collect(Collectors.groupingBy(CapabilityDefinition::getOwnerId));
- capByInstance.forEach((instanceId, capabilityDefinitions) -> { setCapabilitiesOnInstanceByType(instances.get(instanceId), capabilityType, capabilityDefinitions); });
- }
-
- private void setRequirementsOnInstance(Map<String, ComponentInstance> instances, String requirementType, List<RequirementDefinition> requirements) {
- Map<String, List<RequirementDefinition>> reqByInstance = requirements.stream().collect(Collectors.groupingBy(RequirementDefinition::getOwnerId));
- reqByInstance.forEach((instanceId, reqDefinitions) -> { setRequirementsOnInstanceByType(instances.get(instanceId), requirementType, reqDefinitions);});
- }
-
- private void setCapabilitiesOnInstanceByType(ComponentInstance instance, String capabilityType, List<CapabilityDefinition> capabilityDefinitions) {
- instance.getCapabilities().putIfAbsent(capabilityType, new ArrayList<>());
- instance.getCapabilities().get(capabilityType).addAll(capabilityDefinitions);
- }
-
- private void setRequirementsOnInstanceByType(ComponentInstance instance, String requirementType, List<RequirementDefinition> reqDefinitions) {
- instance.getRequirements().putIfAbsent(requirementType, new ArrayList<>());
- instance.getRequirements().get(requirementType).addAll(reqDefinitions);
- }
-
- private Map<String, ComponentInstance> groupInstancesById(T element) {
- return element.getComponentInstances()
- .stream()
- .collect(Collectors.toMap(ComponentInstance::getUniqueId, Function.identity()));
- }
-
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationConfigManager.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationConfigManager.java
index facb9d70f2..79b36f0004 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationConfigManager.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationConfigManager.java
@@ -16,12 +16,22 @@ public class ValidationConfigManager {
return outputFilePath;
}
- public static void setOutputFilePath(String outputFilePath) {
- ValidationConfigManager.outputFilePath = outputFilePath;
+ public static void setOutputFilePath(String outputPath) {
+ ValidationConfigManager.outputFilePath = outputPath+ "/reportOutput.txt";
}
private static String outputFilePath;
+ public static String getCsvReportFilePath() {
+ return csvReportFilePath;
+ }
+
+ public static void setCsvReportFilePath(String outputPath) {
+ ValidationConfigManager.csvReportFilePath = outputPath +"/csvSummary_"+System.currentTimeMillis()+".csv";
+ }
+
+ private static String csvReportFilePath = "summary.csv";
+
public static Properties setValidationConfiguration(String path){
InputStream input = null;
try {
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 87b27c7369..0e6b2c7d16 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfiguration.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/config/ValidationToolConfiguration.java
@@ -1,12 +1,12 @@
package org.openecomp.sdc.asdctool.impl.validator.config;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.MigrationTitanStrategy;
import org.openecomp.sdc.asdctool.impl.validator.tasks.artifacts.ArtifactValidationUtils;
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.executers.ServiceValidatorExecuter;
import org.openecomp.sdc.asdctool.impl.validator.executers.VfValidatorExecuter;
import org.openecomp.sdc.asdctool.impl.validator.ValidationToolBL;
+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;
@@ -16,8 +16,6 @@ import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
import org.openecomp.sdc.be.model.DerivedNodeTypeResolver;
import org.openecomp.sdc.be.model.jsontitan.operations.*;
-import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator;
-import org.openecomp.sdc.be.model.operations.impl.ToscaDefinitionPathCalculatorImpl;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -38,6 +36,9 @@ public class ValidationToolConfiguration {
public ServiceArtifactValidationTask serviceArtifactValidationTask() { return new ServiceArtifactValidationTask();}
@Bean
+ public ModuleJsonTask moduleJsonTask() { return new ModuleJsonTask();}
+
+ @Bean
public ValidationToolBL validationToolBL() {
return new ValidationToolBL();
}
@@ -111,11 +112,6 @@ public class ValidationToolConfiguration {
return new CategoryOperation();
}
- @Bean(name = "tosca-path-calculator")
- public ToscaDefinitionPathCalculator pathCalculator() {
- return new ToscaDefinitionPathCalculatorImpl();
- }
-
@Bean(name = "artifacts-operation")
public ArtifactsOperations artifactsOperation() {
return new ArtifactsOperations();
diff --git a/asdctool/src/main/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 16a479dc75..15f25738c0 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
@@ -3,6 +3,7 @@ package org.openecomp.sdc.asdctool.impl.validator.executers;
import fj.data.Either;
import org.openecomp.sdc.asdctool.impl.validator.tasks.TopologyTemplateValidationTask;
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.types.VertexTypeEnum;
@@ -29,9 +30,6 @@ public class TopologyTemplateValidatorExecuter {
protected TitanDao titanDao;
@Autowired
- protected ToscaOperationFacade toscaOperationFacade;
-
- @Autowired
protected TopologyTemplateOperation topologyTemplateOperation;
protected String name;
@@ -44,10 +42,6 @@ public class TopologyTemplateValidatorExecuter {
return name;
}
- public void reportValidateTaskStatus(TopologyTemplateValidationTask validationTask, boolean success, GraphVertex vertexScanned) {
- ReportManager.reportValidationTaskStatus(vertexScanned, validationTask.getTaskName(), validationTask.getTaskResultStatus(), success);
- }
-
protected List<GraphVertex> getVerticesToValidate(ComponentTypeEnum type) {
Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
props.put(GraphPropertyEnum.COMPONENT_TYPE, type.name());
@@ -58,7 +52,7 @@ public class TopologyTemplateValidatorExecuter {
Either<List<GraphVertex>, TitanOperationStatus> results = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props);
if (results.isRight()) {
System.out.println("getVerticesToValidate failed "+ results.right().value());
- return new ArrayList<GraphVertex>();
+ return new ArrayList<>();
}
System.out.println("getVerticesToValidate: "+results.left().value().size()+" vertices to scan");
return results.left().value();
@@ -69,19 +63,24 @@ public class TopologyTemplateValidatorExecuter {
Set<String> failedTasks = new HashSet<>();
Set<String> successTasks = new HashSet<>();
boolean successAllVertices = true;
+ int vertexNum = 0;
+ int verticesSize = vertices.size();
+
for (GraphVertex vertex: vertices) {
+ vertexNum++;
boolean successAllTasks = true;
for (TopologyTemplateValidationTask task: tasks) {
ReportManager.reportStartTaskRun(vertex, task.getTaskName());
- boolean success = task.validate(vertex);
- if (!success) {
+ VertexResult result = task.validate(vertex);
+ if (!result.getStatus()) {
failedTasks.add(task.getTaskName());
successAllVertices = false;
successAllTasks = false;
- } else {
+ } else if (successAllTasks && vertexNum == verticesSize) {
successTasks.add(task.getTaskName());
}
- reportValidateTaskStatus(task, success, vertex);
+ ReportManager.printValidationTaskStatus(vertex, task.getTaskName(), result.getStatus());
+ ReportManager.reportTaskEnd(vertex.getUniqueId(), task.getTaskName(), result);
}
String componentScanStatus = successAllTasks? "success" : "failed";
System.out.println("Topology Template "+vertex.getUniqueId()+" Validation finished with "+componentScanStatus);
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/TopologyTemplateValidationTask.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/TopologyTemplateValidationTask.java
index 6ca012546b..d73b197ac7 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/TopologyTemplateValidationTask.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/TopologyTemplateValidationTask.java
@@ -1,12 +1,13 @@
package org.openecomp.sdc.asdctool.impl.validator.tasks;
+import org.openecomp.sdc.asdctool.impl.validator.utils.VertexResult;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
/**
* Created by chaya on 7/5/2017.
*/
public interface TopologyTemplateValidationTask {
- boolean validate(GraphVertex vertex);
+ VertexResult validate(GraphVertex vertex);
String getTaskName();
String getTaskResultStatus();
void setTaskResultStatus(String status);
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 dfdeec8c67..faccd647c2 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
@@ -27,18 +27,21 @@ public class ArtifactValidationUtils {
@Autowired
private TopologyTemplateOperation topologyTemplateOperation;
- public boolean validateArtifactsAreInCassandra(GraphVertex vertex, String taskName, List<ArtifactDataDefinition> artifacts) {
- boolean allArtifactsExist = true;
+ public ArtifactsVertexResult validateArtifactsAreInCassandra(GraphVertex vertex, String taskName, List<ArtifactDataDefinition> artifacts) {
+ ArtifactsVertexResult result = new ArtifactsVertexResult(true);
for(ArtifactDataDefinition artifact:artifacts) {
boolean isArtifactExist = isArtifcatInCassandra(artifact.getEsId());
String status = isArtifactExist ? "Artifact " + artifact.getEsId() + " is in Cassandra" :
"Artifact " + artifact.getEsId() + " doesn't exist in Cassandra";
+
ReportManager.writeReportLineToFile(status);
if (!isArtifactExist) {
- allArtifactsExist = false;
+ ReportManager.addFailedVertex(taskName, vertex.getUniqueId());
+ result.setStatus(false);
+ result.addNotFoundArtifact(artifact.getUniqueId());
}
}
- return allArtifactsExist;
+ return result;
}
public boolean isArtifcatInCassandra(String uniueId) {
@@ -51,7 +54,6 @@ public class ArtifactValidationUtils {
}
Long count = countOfArtifactsEither.left().value();
if (count <1) {
- //System.out.print("Artifact "+uniueId+" count is: "+count);
return false;
}
return true;
@@ -67,14 +69,16 @@ public class ArtifactValidationUtils {
return artifacts;
}
- public boolean validateTopologyTemplateArtifacts(GraphVertex vertex, String taskName) {
+ public ArtifactsVertexResult validateTopologyTemplateArtifacts(GraphVertex vertex, String taskName) {
+ ArtifactsVertexResult result = new ArtifactsVertexResult();
ComponentParametersView paramView = new ComponentParametersView();
paramView.disableAll();
paramView.setIgnoreArtifacts(false);
paramView.setIgnoreComponentInstances(false);
Either<ToscaElement, StorageOperationStatus> toscaElementEither = topologyTemplateOperation.getToscaElement(vertex.getUniqueId(), paramView);
if (toscaElementEither.isRight()) {
- return false;
+ result.setStatus(false);
+ return result;
}
TopologyTemplate element = (TopologyTemplate) toscaElementEither.left().value();
Map<String, ArtifactDataDefinition> deploymentArtifacts = element.getDeploymentArtifacts();
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ArtifactsVertexResult.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ArtifactsVertexResult.java
new file mode 100644
index 0000000000..c010148644
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ArtifactsVertexResult.java
@@ -0,0 +1,30 @@
+package org.openecomp.sdc.asdctool.impl.validator.tasks.artifacts;
+
+import org.openecomp.sdc.asdctool.impl.validator.utils.VertexResult;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Created by chaya on 7/25/2017.
+ */
+public class ArtifactsVertexResult extends VertexResult{
+ Set<String> notFoundArtifacts = new HashSet<>();
+
+ public ArtifactsVertexResult() {
+
+ }
+
+ public ArtifactsVertexResult(boolean status) {
+ super(status);
+ }
+
+ public void addNotFoundArtifact(String artifactId) {
+ notFoundArtifacts.add(artifactId);
+ }
+
+ @Override
+ public String getResult() {
+ return notFoundArtifacts.toString();
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ServiceArtifactValidationTask.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ServiceArtifactValidationTask.java
index 410691fb47..0a224f8d84 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ServiceArtifactValidationTask.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/ServiceArtifactValidationTask.java
@@ -20,7 +20,7 @@ public class ServiceArtifactValidationTask extends ServiceValidationTask {
}
@Override
- public boolean validate(GraphVertex vertex) {
+ public ArtifactsVertexResult validate(GraphVertex vertex) {
return artifactValidationUtils.validateTopologyTemplateArtifacts(vertex, getTaskName());
}
}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/VfArtifactValidationTask.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/VfArtifactValidationTask.java
index 01bc26fe2b..bb25d25e2b 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/VfArtifactValidationTask.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/artifacts/VfArtifactValidationTask.java
@@ -1,6 +1,7 @@
package org.openecomp.sdc.asdctool.impl.validator.tasks.artifacts;
import org.openecomp.sdc.asdctool.impl.validator.tasks.VfValidationTask;
+import org.openecomp.sdc.asdctool.impl.validator.utils.VertexResult;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
import org.springframework.beans.factory.annotation.Autowired;
@@ -18,11 +19,11 @@ public class VfArtifactValidationTask extends VfValidationTask {
protected TopologyTemplateOperation topologyTemplateOperation;
public VfArtifactValidationTask() {
- this.name = "Artifact Validation Task";
+ this.name = "VF Artifact Validation Task";
}
@Override
- public boolean validate(GraphVertex vertex) {
+ public VertexResult validate(GraphVertex vertex) {
return artifactValidationUtils.validateTopologyTemplateArtifacts(vertex, getTaskName());
}
}
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
new file mode 100644
index 0000000000..187359f127
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/tasks/moduleJson/ModuleJsonTask.java
@@ -0,0 +1,95 @@
+package org.openecomp.sdc.asdctool.impl.validator.tasks.moduleJson;
+
+import fj.data.Either;
+import org.apache.cassandra.cql3.CQL3Type;
+import org.openecomp.sdc.asdctool.impl.validator.tasks.ServiceValidationTask;
+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.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
+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.operations.api.StorageOperationStatus;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ * Created by chaya on 7/18/2017.
+ */
+public class ModuleJsonTask extends ServiceValidationTask {
+
+ @Autowired
+ private TopologyTemplateOperation topologyTemplateOperation;
+
+ public ModuleJsonTask() {
+ this.name = "Service Module json Validation Task";
+ }
+
+ @Override
+ public VertexResult validate(GraphVertex vertex) {
+ if (!isAfterSubmitForTesting(vertex)) {
+ return new VertexResult(true);
+ }
+
+ ComponentParametersView paramView = new ComponentParametersView();
+ paramView.disableAll();
+ paramView.setIgnoreArtifacts(false);
+ paramView.setIgnoreGroups(false);
+ paramView.setIgnoreComponentInstances(false);
+ Either<ToscaElement, StorageOperationStatus> toscaElementEither = topologyTemplateOperation.getToscaElement(vertex.getUniqueId(), paramView);
+ if (toscaElementEither.isRight()) {
+ return new VertexResult(false);
+ }
+ TopologyTemplate element = (TopologyTemplate) toscaElementEither.left().value();
+ Map<String, MapGroupsDataDefinition> instGroups = element.getInstGroups();
+ Map<String, MapArtifactDataDefinition> instDeploymentArtifacts = element.getInstDeploymentArtifacts();
+
+ for (Map.Entry<String, MapGroupsDataDefinition> pair : Optional.ofNullable(instGroups).orElse(Collections.emptyMap()).entrySet()) {
+ MapGroupsDataDefinition groups = pair.getValue();
+ if (groups != null && !groups.getMapToscaDataDefinition().isEmpty()) {
+ return new VertexResult(findCoordinateModuleJson(pair, instDeploymentArtifacts, vertex));
+ }
+ return new VertexResult(true);
+ }
+ return new VertexResult(true);
+ }
+
+ private boolean findCoordinateModuleJson(Map.Entry<String, MapGroupsDataDefinition> pair, Map<String, MapArtifactDataDefinition> instDeploymentArtifacts, GraphVertex vertex) {
+ String groupKey = pair.getKey();
+ String[] split = groupKey.split("\\.");
+ String instanceName = split[split.length-1];
+ MapArtifactDataDefinition deploymentsArtifacts = instDeploymentArtifacts.get(groupKey);
+ if (deploymentsArtifacts != null && !deploymentsArtifacts.getMapToscaDataDefinition().isEmpty()) {
+ List<ArtifactDataDefinition> moduleJsonArtifacts = deploymentsArtifacts.getMapToscaDataDefinition().values().stream().filter(artifact -> {
+ String artifactName = artifact.getArtifactName();
+ if (artifactName.startsWith(instanceName) && artifactName.endsWith("modules.json")) {
+ return true;
+ }
+ return false;
+ }).collect(Collectors.toList());
+ if (moduleJsonArtifacts.size() > 0) {
+ String status = "Instance "+instanceName+" has a corresponding modules.json file: "+moduleJsonArtifacts.get(0).getArtifactName();
+ ReportManager.writeReportLineToFile(status);
+ return true;
+ }
+ }
+ String status = "Instance "+instanceName+" doesn't have a corresponding modules.json file";
+ ReportManager.writeReportLineToFile(status);
+ ReportManager.addFailedVertex(getTaskName(), vertex.getUniqueId());
+ return false;
+ }
+
+ private boolean isAfterSubmitForTesting(GraphVertex vertex){
+ List allowedStates = new ArrayList<>(Arrays.asList(LifecycleStateEnum.READY_FOR_CERTIFICATION.name(),
+ LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name(), LifecycleStateEnum.CERTIFIED.name()));
+ return allowedStates.contains(vertex.getMetadataProperty(GraphPropertyEnum.STATE));
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/ReportManager.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/ReportManager.java
index 1fdde7dd80..64bea12957 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/ReportManager.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/ReportManager.java
@@ -1,7 +1,6 @@
package org.openecomp.sdc.asdctool.impl.validator.utils;
import org.apache.commons.lang.text.StrBuilder;
-import org.openecomp.sdc.asdctool.impl.validator.tasks.TopologyTemplateValidationTask;
import org.openecomp.sdc.asdctool.impl.validator.config.ValidationConfigManager;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
@@ -9,37 +8,59 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
+import java.util.*;
/**
* Created by chaya on 7/5/2017.
*/
public class ReportManager {
- private static List<ValidationTaskResult> taskResults;
private static String reportOutputFilePath;
+ private static String csvReportFilePath;
+ private static Map<String, Set<String>> failedVerticesPerTask = new HashMap<>();
+ private static Map<String, Map<String, VertexResult>> resultsPerVertex = new HashMap<>();
public ReportManager() {
try {
- taskResults = new ArrayList<>();
- // open file for first time
- reportOutputFilePath = ValidationConfigManager.getOutputFilePath();
- StrBuilder sb = new StrBuilder();
- sb.appendln("-----------------------Validation Tool Results:-------------------------");
- Files.write(Paths.get(reportOutputFilePath), sb.toString().getBytes());
+ initCsvFile();
+ initReportFile();
} catch (IOException e) {
e.printStackTrace();
}
}
- public static void reportValidationTaskStatus(GraphVertex vertexScanned, String taskName, String taskResultMessage, boolean success) {
- taskResults.add(new ValidationTaskResult(vertexScanned, taskName, taskResultMessage, success));
- printValidationTaskStatus(vertexScanned, taskName, success);
+ private void initReportFile() throws IOException {
+ reportOutputFilePath = ValidationConfigManager.getOutputFilePath();
+ StrBuilder sb = new StrBuilder();
+ sb.appendln("-----------------------Validation Tool Results:-------------------------");
+ Files.write(Paths.get(reportOutputFilePath), sb.toString().getBytes());
+ }
+
+ private void initCsvFile() throws IOException {
+ csvReportFilePath = ValidationConfigManager.getCsvReportFilePath();
+ StrBuilder sb = new StrBuilder();
+ sb.append("Vertex ID,"+"Task Name,"+"Success,"+"Result Details"+","+"Result Description");
+ sb.appendNewLine();
+ Files.write(Paths.get(csvReportFilePath), sb.toString().getBytes());
}
- private static void printValidationTaskStatus(GraphVertex vertexScanned, String taskName, boolean success) {
+ public static void reportTaskEnd(String vertexId, String taskName, VertexResult result) {
+ Map<String, VertexResult> vertexTasksResults =
+ Optional.ofNullable(resultsPerVertex.get(vertexId)).orElse(new HashMap<>());
+ vertexTasksResults.put(taskName, result);
+ resultsPerVertex.put(vertexId, vertexTasksResults);
+ }
+
+ public static void addFailedVertex (String taskName, String vertexId) {
+ Set<String> failedVertices = failedVerticesPerTask.get(taskName);
+ if (failedVertices == null) {
+ failedVertices = new HashSet<>();
+ }
+ failedVertices.add(vertexId);
+ failedVerticesPerTask.put(taskName, failedVertices);
+ }
+
+ public static void printValidationTaskStatus(GraphVertex vertexScanned, String taskName, boolean success) {
String successStatus = success ? "success" : "failed";
String line = "-----------------------Vertex: "+vertexScanned.getUniqueId()+", Task " + taskName + " " +successStatus+"-----------------------";
StrBuilder sb = new StrBuilder();
@@ -49,16 +70,6 @@ public class ReportManager {
writeReportLineToFile(line);
}
- public static void reportValidationTaskSummary(TopologyTemplateValidationTask task, int numOfFailedComponents, int numOfSuccessComponents) {
- StrBuilder sb = new StrBuilder();
- sb.appendNewLine();
- sb.appendln("-----------------------Task " + task.getTaskName() + " Validation Summary-----------------------");
- sb.appendln("Num of failed components: "+ numOfFailedComponents);
- sb.appendln("Num of success components: "+ numOfSuccessComponents);
- sb.appendln("Total components scanned: " + numOfFailedComponents+numOfSuccessComponents);
- writeReportLineToFile(sb.toString());
- }
-
public static void writeReportLineToFile(String message) {
try {
Files.write(Paths.get(reportOutputFilePath), new StrBuilder().appendNewLine().toString().getBytes(), StandardOpenOption.APPEND);
@@ -90,4 +101,32 @@ public class ReportManager {
sb.appendln("-----------------------Vertex: "+vertex.getUniqueId()+", Task " + taskName + " Started-----------------------");
writeReportLineToFile(sb.toString());
}
+
+ public static void reportEndOfToolRun() {
+ StrBuilder sb = new StrBuilder();
+ sb.appendNewLine().appendNewLine();
+ sb.appendln("-----------------------------------Validator Tool Summary-----------------------------------");
+ failedVerticesPerTask.forEach((taskName, failedVertices) -> {
+ sb.append("Task: " + taskName);
+ sb.appendNewLine();
+ sb.append("FailedVertices: " + failedVertices);
+ sb.appendNewLine();
+ });
+ writeReportLineToFile(sb.toString());
+ printAllResults();
+ }
+
+ public static void printAllResults() {
+ resultsPerVertex.forEach((vertex, tasksResults)->{
+ tasksResults.forEach((task, result) -> {
+ try {
+ String resultLine = vertex +","+task+","+result.getStatus()+","+result.getResult();
+ Files.write(Paths.get(csvReportFilePath), resultLine.getBytes(), StandardOpenOption.APPEND);
+ Files.write(Paths.get(csvReportFilePath), new StrBuilder().appendNewLine().toString().getBytes(), StandardOpenOption.APPEND);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ });
+ });
+ }
}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/VertexResult.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/VertexResult.java
new file mode 100644
index 0000000000..4fe8ec30f5
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/validator/utils/VertexResult.java
@@ -0,0 +1,30 @@
+package org.openecomp.sdc.asdctool.impl.validator.utils;
+
+/**
+ * Created by chaya on 7/25/2017.
+ */
+public class VertexResult {
+
+ boolean status;
+
+ public VertexResult() {
+
+ }
+
+ public VertexResult(boolean status) {
+ this.status = status;
+ }
+
+ public boolean getStatus() {
+ return status;
+ }
+
+ public void setStatus(boolean status) {
+ this.status = status;
+ }
+
+ public String getResult() {
+ return String.valueOf(status);
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/EsToCassandraDataMigrationMenu.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/EsToCassandraDataMigrationMenu.java
index b82b62b551..d563f2cf33 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/EsToCassandraDataMigrationMenu.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/EsToCassandraDataMigrationMenu.java
@@ -32,7 +32,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
public class EsToCassandraDataMigrationMenu {
- private static Logger log = LoggerFactory.getLogger(MigrationMenu.class.getName());
+ private static Logger log = LoggerFactory.getLogger(EsToCassandraDataMigrationMenu.class.getName());
public static void main(String[] args) throws Exception {
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/MigrationMenu.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/MigrationMenu.java
deleted file mode 100644
index 600ebf848a..0000000000
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/MigrationMenu.java
+++ /dev/null
@@ -1,345 +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.main;
-
-import java.util.Arrays;
-import java.util.Optional;
-
-import org.openecomp.sdc.asdctool.impl.PopulateComponentCache;
-import org.openecomp.sdc.asdctool.impl.migration.v1604.AppConfig;
-import org.openecomp.sdc.asdctool.impl.migration.v1604.DerivedFromAlignment;
-import org.openecomp.sdc.asdctool.impl.migration.v1604.GroupsAlignment;
-import org.openecomp.sdc.asdctool.impl.migration.v1604.ServiceMigration;
-import org.openecomp.sdc.asdctool.impl.migration.v1604.VfcNamingAlignment;
-import org.openecomp.sdc.asdctool.impl.migration.v1607.CsarMigration;
-import org.openecomp.sdc.asdctool.impl.migration.v1610.TitanFixUtils;
-import org.openecomp.sdc.asdctool.impl.migration.v1610.ToscaArtifactsAlignment;
-import org.openecomp.sdc.asdctool.impl.migration.v1702.Migration1702;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.*;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.common.api.ConfigurationSource;
-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.context.annotation.AnnotationConfigApplicationContext;
-
-public class MigrationMenu {
-
- private static Logger log = LoggerFactory.getLogger(MigrationMenu.class.getName());
- private static final String SERVICE_MIGARTION_BEAN = "serviceMigrationBean";
-
- private static enum MigrationOperationEnum {
- MIGRATION_1602_1604("migrate-1602-1604", SERVICE_MIGARTION_BEAN),
- ALIGN_DERIVED_FROM_1604("align-derived-from-1604", "derivedFromAlignment"),
- MIGRATE_1604_1607("migrate-1604-1607", SERVICE_MIGARTION_BEAN),
- ALIGN_VFC_NAMES_1604("align-vfc-names-1604", "vfcNamingAlignmentBean"),
- TEST_REMOVE_HEAT_PLACEHOLDERS("testremoveheatplaceholders", SERVICE_MIGARTION_BEAN),
- TEST_ADD_GROUP_UUIDS("testaddgroupuuids", SERVICE_MIGARTION_BEAN),
- ALIGN_GROUPS("align-groups", "groupsAlignment"),
- CLEAN_CSAR("clean-csar", "csarMigration"),
- POPULATE_COMPONENT_CACHE("populate-component-cache", "populateComponentCache"),
- FIX_PROPERTIES("fix-properties", "titanFixUtils"),
- ALIGN_TOSCA_ARTIFACTS("align-tosca-artifacts", "toscaArtifactsAlignment"),
- FIX_ICONS("fix-icons", "titanFixUtils"),
- MIGRATION_1610_1702("migrate-1610-1702", "migration1702"),
- MIGRATION_1702_1707("migrate-1702-1707", "migration1707"),
- DISTRIBUTION_STATUS_UPDATE_1707("distribution-status-update-1707", "distributionStatusUpdate"),
- VFMODULES_PROPERTIES_ADDING("vfModules-properties-adding", "vfModulesPropertiesAdding"),
- MIGRATION_1707_RELATIONS_FIX("fix-relations-after-migration-1707", "migration1707relationsFix"),
- MIGRATION_1707_VNF_FIX("fix-vnf-after-migration-1707", "migration1707vnfFix"),
- MIGRATION_1707_UUID_FIX("fix-UUID-1707", "migration1707UuidFix"),
- MIGRATION_1707_MISSING_INFO_FIX("fix-missing-info-1707", "migration1707MissingInfoFix");
- // UPDATE_DATA_TYPES("update_data_types", "updateDataTypes");
-
- private String value, beanName;
-
- public static MigrationOperationEnum findByValue(String value) {
- Optional<MigrationOperationEnum> optionalFound = Arrays.asList(MigrationOperationEnum.values()).stream().filter(e -> e.getValue().equalsIgnoreCase(value)).findAny();
- return optionalFound.isPresent() ? optionalFound.get() : null;
- }
-
- MigrationOperationEnum(String value, String beanName) {
- this.value = value;
- this.beanName = beanName;
- }
-
- public String getValue() {
- return value;
- }
-
- public String getBeanName() {
- return beanName;
- }
- };
-
- //arguments will be [operation] [version] [config path] [align derived - optional]
- //example : migrate-1610-1702 1702 /home/config
- public static void main(String[] args) throws Exception {
-
- if (args == null || args.length < 3) {
- usageAndExit();
- }
- MigrationOperationEnum operationEnum = MigrationOperationEnum.findByValue(args[0]);
- String appConfigDir = args[2];
- String dataInputFileDir = null;
- if (operationEnum == MigrationOperationEnum.ALIGN_DERIVED_FROM_1604 ) {
- dataInputFileDir = args[3];
- }
- log.info("Run with configuration folder {}", appConfigDir);
- AnnotationConfigApplicationContext context = initContext(appConfigDir);
- try {
- ServiceMigration serviceMigration = (ServiceMigration) context.getBean(SERVICE_MIGARTION_BEAN);
- switch (operationEnum) {
- case MIGRATION_1602_1604:
- log.info("Start Titan migration from 1602 version to 1604");
- if (serviceMigration.migrate1602to1604(appConfigDir)) {
- log.info("Titan migration from 1602 version to 1604 was finished successfull");
- System.exit(0);
- } else {
- log.info("Titan migration from 1602 version to 1604 was failed");
- System.exit(2);
- }
- break;
- case MIGRATE_1604_1607:
- log.info("Start Titan migration from 1604 version to 1607");
- if (serviceMigration.migrate1604to1607(appConfigDir)) {
- log.info("Titan migration from 1604 version to 1607 was finished successfull");
- System.exit(0);
- } else {
- log.info("Titan migration from 1604 version to 1607 was failed");
- System.exit(2);
- }
- break;
- case ALIGN_VFC_NAMES_1604:
- VfcNamingAlignment vfcNamingAlignment = (VfcNamingAlignment) context.getBean(operationEnum.getBeanName());
- log.info("Start VFC naming alignment on 1604");
- if (vfcNamingAlignment.alignVfcNames1604(appConfigDir)) {
- log.info("VFC naming alignment on 1604 was finished successfull");
- System.exit(0);
- } else {
- log.info("VFC naming alignment on 1604 was failed");
- System.exit(2);
- }
- break;
- case TEST_REMOVE_HEAT_PLACEHOLDERS:
- boolean check = serviceMigration.testRemoveHeatPlaceHolders(appConfigDir);
- if (check == true) {
- System.exit(0);
- } else {
- System.exit(2);
- }
- break;
- case TEST_ADD_GROUP_UUIDS:
- check = serviceMigration.testAddGroupUuids(appConfigDir);
- if (check == true) {
- System.exit(0);
- } else {
- System.exit(2);
- }
- break;
- case ALIGN_DERIVED_FROM_1604:
- DerivedFromAlignment derivedFromAlignment = (DerivedFromAlignment) context.getBean(operationEnum.getBeanName());
- log.info("Start derived from alignment on 1604");
- if (derivedFromAlignment.alignDerivedFrom1604(appConfigDir, dataInputFileDir)) {
- log.info("Derived from alignment on 1604 was finished successfull");
- System.exit(0);
- } else {
- log.info("Derived from alignment on 1604 was failed");
- System.exit(2);
- }
- break;
- case ALIGN_GROUPS:
- GroupsAlignment groupsAlignment = (GroupsAlignment) context.getBean(operationEnum.getBeanName());
- log.debug("Start derived from alignment on 1604");
- if (groupsAlignment.alignGroups(appConfigDir)) {
- log.debug("Groups alignment was finished successfull");
- System.exit(0);
- } else {
- log.debug("Groups alignment was failed");
- System.exit(2);
- }
- break;
- case CLEAN_CSAR:
- log.info("Start remove CSAR resources");
- CsarMigration csarMigration = (CsarMigration) context.getBean(operationEnum.getBeanName());
- if (csarMigration.removeCsarResources()) {
- log.info("Remove CSAR resources finished successfully");
- System.exit(0);
- } else {
- log.info("Remove CSAR resources failed");
- System.exit(2);
- }
- break;
- case POPULATE_COMPONENT_CACHE:
- PopulateComponentCache populateComponentCache = (PopulateComponentCache) context.getBean(operationEnum.getBeanName());
- populateComponentCache.populateCache();
- System.exit(0);
- break;
- case FIX_PROPERTIES:
- log.debug("Start fix capability properties types");
- TitanFixUtils titanFixUtils = (TitanFixUtils) context.getBean(operationEnum.getBeanName());
- if (titanFixUtils.fixCapabiltyPropertyTypes()) {
- log.debug("Fix capability properties types finished successfully");
- System.exit(0);
- } else {
- log.debug("Fix capability properties types failed");
- System.exit(2);
- }
- break;
- case FIX_ICONS:
- log.info("Start fix icons of vl and eline");
- titanFixUtils = (TitanFixUtils) context.getBean(operationEnum.getBeanName());
- if (titanFixUtils.fixIconsInNormatives()) {
- log.info("Fix icons of vl and eline finished successfully");
- System.exit(0);
- } else {
- log.info("Fix icons of vl and eline failed");
- System.exit(2);
- }
- break;
- case ALIGN_TOSCA_ARTIFACTS:
- log.info("Start align tosca artifacts");
- ToscaArtifactsAlignment toscaArtifactsAlignment = (ToscaArtifactsAlignment) context.getBean(operationEnum.getBeanName());
- boolean isSuccessful = toscaArtifactsAlignment.alignToscaArtifacts();
- if (isSuccessful) {
- log.info("Tosca Artifacts alignment was finished successfully");
- System.exit(0);
- } else {
- log.info("Tosca Artifacts alignment has failed");
- System.exit(2);
- }
- break;
- case MIGRATION_1610_1702:
- log.info("Start SDC migration from 1610 to 1702");
- Migration1702 migration = (Migration1702) context.getBean(operationEnum.getBeanName());
- isSuccessful = migration.migrate(appConfigDir);
- if (isSuccessful) {
- log.info("SDC migration from 1610 to 1702 was finished successful");
- System.exit(0);
- } else{
- log.info("SDC migration from 1610 to 1702 has failed");
- System.exit(2);
- }
-
- break;
- case MIGRATION_1702_1707://this migration is currently not needed, but will be commented out for production env
-// log.info("Start SDC migration from 1702 to 1707");
- Migration1707 migration1707 = (Migration1707) context.getBean(operationEnum.getBeanName());
- isSuccessful = migration1707.migrate();
- if (isSuccessful) {
- log.info("SDC migration from 1702 to 1707 was finished successfully");
- System.exit(0);
- } else{
- log.info("SDC migration from 1702 to 1707 has failed");
- System.exit(2);
- }
- System.exit(0);
- break;
- case VFMODULES_PROPERTIES_ADDING://this migration is currently not needed, but will be commented out for production env
- log.info("Start adding new properties to vfModules");
- VfModulesPropertiesAdding migrationVfModulesProperties = (VfModulesPropertiesAdding) context.getBean(operationEnum.getBeanName());
- isSuccessful = migrationVfModulesProperties.migrate(args[1]);
- if (isSuccessful) {
- log.info("Adding new properties to vfModules was finished successfully");
- System.exit(0);
- } else{
- log.info("Adding new properties to vfModules has failed");
- System.exit(2);
- }
- System.exit(0);
- break;
- case MIGRATION_1707_UUID_FIX:
- if (args == null || args.length < 5) {
- System.out.println("Usage: fix-UUID-1707 <configuration dir> <all/distributed_only> <services/service_vf/fix/fix_only_services>");
- System.exit(1);
- }
- String fixServices = args[3];
- String runMode = args[4];
- log.info("Start fixing artifact UUID after 1707 migration with arguments run with configuration [{}] , for [{}] services", runMode, fixServices);
-
- Migration1707ArtifactUuidFix migrationFix = (Migration1707ArtifactUuidFix) context.getBean(operationEnum.getBeanName());
- isSuccessful = migrationFix.migrate(fixServices, runMode);
- if (isSuccessful) {
- log.info("Fixing artifacts UUID for 1707 was finished successfully");
- } else{
- log.info("Fixing artifacts UUID for 1707 has failed");
- System.exit(2);
- }
- System.exit(0);
- break;
- case MIGRATION_1707_MISSING_INFO_FIX:
-
- log.info("Start fixing missing group and instance info after 1707 migration");
-
- Migration1707MissingInfoFix migration1707Fix = (Migration1707MissingInfoFix) context.getBean(operationEnum.getBeanName());
- isSuccessful = migration1707Fix.migrate();
- if (isSuccessful) {
- log.info("Fixing groups and node templates missing info was finished successfully");
- } else{
- log.info("Fixing groups and node templates missing info has failed");
- System.exit(2);
- }
- System.exit(0);
- break;
- default:
- usageAndExit();
- }
- } catch (Exception t) {
- log.info("Failed {} with exception: {}", operationEnum, t.toString());
- t.printStackTrace();
- log.debug("Error while Running MigrationMenu {}", t.getMessage(), t);
- System.exit(3);
- } finally {
- context.close();
- }
- }
-
- private static AnnotationConfigApplicationContext initContext(String appConfigDir) {
- ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
- ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
- AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class, Migration1707Config.class);
- return context;
- }
-
- private static void usageAndExit() {
- MigrationUsage();
- System.exit(1);
- }
-
- private static void MigrationUsage() {
- System.out.println("Usage: migrate-1602-1604 <configuration dir>");
- System.out.println("Usage: migrate-1604-1607 <configuration dir>");
- System.out.println("Usage: align-vfc-names-1604 <configuration dir>");
- System.out.println("Usage: align-derived-from-1604 <configuration dir> <data_input_file dir>");
- System.out.println("Usage: align-groups <configuration dir>");
- System.out.println("Usage: fix-properties <configuration dir>");
- System.out.println("Usage: migrate-1610-1702 <configuration dir>");
- System.out.println("Usage: migrate-1702-1707 <configuration dir>");
- System.out.println("Usage: update_data_types <configuration dir> <data_types_input_file path>");
- System.out.println("Usage: distribution-status-update-1707");
- System.out.println("Usage: vfModules-properties-adding <group_types_input_file path> <configuration dir>");
- System.out.println("Usage: fix-relations-after-migration-1707 <configuration dir>");
- System.out.println("Usage: fix-vnf-after-migration-1707 <configuration dir>");
- System.out.println("Usage: fix-UUID-1707 <configuration dir> <all/distributed_only> <services/service_vf/fix/fix_only_services>");
- System.out.println("Usage: fix-missing-info-1707 <configuration dir>");
- }
-}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/SdcSchemaFileImport.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/SdcSchemaFileImport.java
index 758dae0342..394683bbc5 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/SdcSchemaFileImport.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/SdcSchemaFileImport.java
@@ -130,9 +130,9 @@ public class SdcSchemaFileImport {
System.err.println("Failed to pack SDC.zip file, error: "+ex);
System.exit(1);
}
-
- //Generation flow end - generating SDC from normatives
+ //Generation flow end - generating SDC from normatives
+
AnnotationConfigApplicationContext context = initContext(appConfigDir);
schemaFilesCassandraDao = (SdcSchemaFilesCassandraDao) context.getBean("sdc-schema-files-cassandra-dao");
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ValidationTool.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ValidationTool.java
index 6b10615ad3..1ee006a49f 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ValidationTool.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/ValidationTool.java
@@ -3,7 +3,7 @@ package org.openecomp.sdc.asdctool.main;
import org.openecomp.sdc.asdctool.impl.validator.ValidationToolBL;
import org.openecomp.sdc.asdctool.impl.validator.config.ValidationConfigManager;
import org.openecomp.sdc.asdctool.impl.validator.config.ValidationToolConfiguration;
-import org.openecomp.sdc.asdctool.impl.migration.v1604.AppConfig;
+import org.openecomp.sdc.asdctool.impl.validator.utils.ReportManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
@@ -21,15 +21,18 @@ public class ValidationTool {
public static void main(String[] args) throws Exception {
- String outputFilePath = args[0];
- ValidationConfigManager.setOutputFilePath(outputFilePath);
+ String outputPath = args[0];
+ ValidationConfigManager.setOutputFilePath(outputPath);
+ ValidationConfigManager.setCsvReportFilePath(outputPath);
String appConfigDir = args[1];
AnnotationConfigApplicationContext context = initContext(appConfigDir);
ValidationToolBL validationToolBL = context.getBean(ValidationToolBL.class);
System.out.println("Start Validation Tool");
- if (validationToolBL.validateAll()) {
+ Boolean result = validationToolBL.validateAll();
+ ReportManager.reportEndOfToolRun();
+ if (result) {
System.out.println("Validation finished successfully");
System.exit(0);
} else {
diff --git a/asdctool/src/main/resources/config/logback.xml b/asdctool/src/main/resources/config/logback.xml
index dadc5254a5..603d894317 100644
--- a/asdctool/src/main/resources/config/logback.xml
+++ b/asdctool/src/main/resources/config/logback.xml
@@ -45,34 +45,10 @@
</encoder>
</appender>
- <appender name="MALFORMED_DATA"
- class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${HOME}/asdctool/logs/${ECOMP-component-name}/${ECOMP-subcomponent-name}/malformed-data.log</file>
-
- <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
- <fileNamePattern>${HOME}/asdctool/logs/${ECOMP-component-name}/${ECOMP-subcomponent-name}/malformed-data.log.%i
- </fileNamePattern>
- <minIndex>1</minIndex>
- <maxIndex>10</maxIndex>
- </rollingPolicy>
-
- <triggeringPolicy
- class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>20MB</maxFileSize>
- </triggeringPolicy>
- <encoder>
- <pattern>${default-log-pattern}</pattern>
- </encoder>
- </appender>
-
-
<root level="INFO">
<appender-ref ref="DEBUG_ROLLING" />
</root>
<logger name="org.openecomp.sdc" level="INFO" />
- <logger name="org.openecomp.sdc.be.model.operations.migration" level="ERROR" >
- <appender-ref ref="MALFORMED_DATA"/>
- </logger>
<logger name="org.openecomp.sdc.asdctool.migration" level="INFO" >
<appender-ref ref="STDOUT"/>
diff --git a/asdctool/src/main/resources/scripts/dataMigration.sh b/asdctool/src/main/resources/scripts/dataMigration.sh
deleted file mode 100644
index e1f4f24a30..0000000000
--- a/asdctool/src/main/resources/scripts/dataMigration.sh
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/bin/bash
-
-##############################
-# Data Migration
-##############################
-
-CURRENT_DIR=`pwd`
-BASEDIR=$(dirname $1)
-
-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.MigrationMenu"
-
-case $1 in
- 1604)
- command="java $JVM_LOG_FILE -cp $JARS $mainClass migrate-1602-1604 $@"
- echo $command
- ;;
- 1607)
- command="sh ./dataMigration1607.sh $@"
- echo $command
- ;;
- 1610)
- command="sh ./dataMigration1610.sh $@"
- echo $command
- ;;
- 1702)
- command="sh ./dataMigration1702.sh $@"
- echo $command
- ;;
- 1707)
- command="sh ./dataMigration1707.sh $@"
- echo $command
- ;;
- *)
- echo "No migration for this version $1"
- ;;
-esac
-
-$command
-result=$?
-
-echo "***********************************"
-echo "***** $result *********************"
-echo "***********************************"
-
-exit $result
-
-
diff --git a/asdctool/src/main/resources/scripts/dataMigration1607.sh b/asdctool/src/main/resources/scripts/dataMigration1607.sh
deleted file mode 100644
index 027852d882..0000000000
--- a/asdctool/src/main/resources/scripts/dataMigration1607.sh
+++ /dev/null
@@ -1,33 +0,0 @@
-#!/bin/bash
-
-##############################
-# Data Migration 1607
-##############################
-
-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.MigrationMenu"
-
-command="java $JVM_LOG_FILE -cp $JARS $mainClass migrate-1604-1607 $@"
-echo $command
-
-$command
-result=$?
-
-echo "***********************************"
-echo "***** $result *********************"
-echo "***********************************"
-
-exit $result
-
-
diff --git a/asdctool/src/main/resources/scripts/dataMigration1610.sh b/asdctool/src/main/resources/scripts/dataMigration1610.sh
deleted file mode 100644
index 45d61adeee..0000000000
--- a/asdctool/src/main/resources/scripts/dataMigration1610.sh
+++ /dev/null
@@ -1,41 +0,0 @@
-#!/bin/bash
-
-##############################
-# Data Migration 1610
-##############################
-
-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.MigrationMenu"
-
-command="java $JVM_LOG_FILE -cp $JARS $mainClass fix-properties $@"
-echo $command
-
-$command
-result=$?
-
-if [ $result -eq 0 ]
-then
- command="java $JVM_LOG_FILE -cp $JARS $mainClass align-tosca-artifacts $@"
- echo $command
- $command
- result=$?
-fi
-
-echo "***********************************"
-echo "***** $result *********************"
-echo "***********************************"
-
-exit $result
-
-
diff --git a/asdctool/src/main/resources/scripts/dataMigration1702.sh b/asdctool/src/main/resources/scripts/dataMigration1702.sh
deleted file mode 100644
index f2bf56e4ef..0000000000
--- a/asdctool/src/main/resources/scripts/dataMigration1702.sh
+++ /dev/null
@@ -1,35 +0,0 @@
-#!/bin/bash
-
-##############################
-# Data Migration 1702
-##############################
-
-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.MigrationMenu"
-
-command="java $JVM_LOG_FILE -cp $JARS $mainClass migrate-1610-1702 $@"
-echo $command
-
-$command
-result=$?
-
-
-
-echo "***********************************"
-echo "***** $result *********************"
-echo "***********************************"
-
-exit $result
-
-
diff --git a/asdctool/src/main/resources/scripts/dataMigration1707.sh b/asdctool/src/main/resources/scripts/dataMigration1707.sh
deleted file mode 100644
index 11a151a7c3..0000000000
--- a/asdctool/src/main/resources/scripts/dataMigration1707.sh
+++ /dev/null
@@ -1,35 +0,0 @@
-#!/bin/bash
-
-##############################
-# Data Migration 1707
-##############################
-
-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.MigrationMenu"
-
-command="java $JVM_LOG_FILE -Xmx6000M -cp $JARS $mainClass migrate-1702-1707 $@"
-echo $command
-
-$command
-result=$?
-
-
-
-echo "***********************************"
-echo "***** $result *********************"
-echo "***********************************"
-
-exit $result
-
-
diff --git a/asdctool/src/main/resources/scripts/validationTool.sh b/asdctool/src/main/resources/scripts/validationTool.sh
index fc82eee72d..58cd7f3f6a 100644
--- a/asdctool/src/main/resources/scripts/validationTool.sh
+++ b/asdctool/src/main/resources/scripts/validationTool.sh
@@ -18,7 +18,8 @@ source ${FULL_PATH}/baseOperation.sh
mainClass="org.openecomp.sdc.asdctool.main.ValidationTool"
-command="java $JVM_LOG_FILE -cp $JARS $mainClass reportOutput.txt /apps/jetty/base/be/config/catalog-be/"
+#command="java $JVM_LOG_FILE -cp $JARS $mainClass reportOutput.txt /home/vagrant/catalog-be/config/catalog-be/"
+command="java $JVM_LOG_FILE -cp $JARS $mainClass . /apps/jetty/base/be/config/catalog-be/"
echo $command
$command
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 e4c75eab05..61f0c02d10 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
@@ -619,7 +619,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left().value()));
}
- return downloadArtifact(csarArtifact);
+ return downloadArtifact(csarArtifact, component);
}
public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
@@ -640,7 +640,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (artifactDefinition.getPayloadData() != null) {
return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
}
- return downloadArtifact(artifactDefinition);
+ return downloadArtifact(artifactDefinition, null);
}
public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
@@ -1526,6 +1526,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
+
Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
@@ -3001,7 +3002,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
// Downloading the artifact
- Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact, null);
if (downloadArtifactEither.isRight()) {
log.debug("Download artifact {} failed", artifactName);
return Either.right(downloadArtifactEither.right().value());
@@ -3062,7 +3063,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.debug("Found deployment artifact {}", artifactName);
deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
// Downloading the artifact
- Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact, service );
if (downloadArtifactEither.isRight()) {
log.debug("Download artifact {} failed", artifactName);
@@ -3167,7 +3168,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
log.debug("Found deployment artifact {}", normalizedArtifactName);
// Downloading the artifact
- Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get());
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get(), service);
if (downloadArtifactEither.isRight()) {
log.debug("Download artifact {} failed", normalizedArtifactName);
return Either.right(downloadArtifactEither.right().value());
@@ -3190,7 +3191,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
}
- return downloadArtifact(artifactDefinition);
+ return downloadArtifact(artifactDefinition, null);
}
private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
@@ -3370,7 +3371,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return auditingAction;
}
- private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
+ private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition, Component component) {
String esArtifactId = artifactDefinition.getEsId();
Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
if (artifactfromES.isRight()) {
@@ -3378,7 +3379,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
- return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
+ ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName());
+ handleAuditing(AuditingActionEnum.DOWNLOAD_ARTIFACT, component, null, null, artifactDefinition, null, artifactDefinition.getArtifactUUID(), responseFormat, null, null);
+
+ return Either.right(responseFormat);
}
ESArtifactData esArtifactData = artifactfromES.left().value();
@@ -3864,7 +3868,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
}
- currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
+ //currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
currArtifact.setListHeatParameters(currentHeatEnvParams);
Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
@@ -4776,7 +4780,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
if (errorWrapper.isEmpty()) {
deploymentArtifact = artifactsList.get(0);
- downloadArtifactEither = downloadArtifact(deploymentArtifact);
+ downloadArtifactEither = downloadArtifact(deploymentArtifact, null);
if (downloadArtifactEither.isRight()) {
log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
errorWrapper.setInnerElement(downloadArtifactEither.right().value());
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
index 1d153e0a5d..5a4961b24f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java
@@ -20,12 +20,8 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Function;
-
+import com.google.gson.JsonElement;
+import fj.data.Either;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -40,26 +36,15 @@ import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupProperty;
-import org.openecomp.sdc.be.model.IComplexDefaultValue;
-import org.openecomp.sdc.be.model.IPropertyInputCommon;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.jsontitan.operations.ArtifactsOperations;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-import org.openecomp.sdc.be.model.operations.api.IAttributeOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
-import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
@@ -80,9 +65,11 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import com.google.gson.JsonElement;
-
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
public abstract class BaseBusinessLogic {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java
index 21f7b3ab7c..33180cd35e 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
@@ -905,11 +905,18 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
} else {
genericTypeToscaName = component.fetchGenericTypeToscaNameFromConfig();
}
- if(null == genericTypeToscaName)
+ log.debug("Fetching generic tosca name {}", genericTypeToscaName);
+ if(null == genericTypeToscaName) {
+ log.debug("Failed to fetch certified node type by tosca resource name {}", genericTypeToscaName);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+
Either<Resource, StorageOperationStatus> findLatestGeneric = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(genericTypeToscaName);
- if(findLatestGeneric.isRight())
+ if(findLatestGeneric.isRight()){
+ log.debug("Failed to fetch certified node type by tosca resource name {}", genericTypeToscaName);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERIC_TYPE_NOT_FOUND, component.assetType(), genericTypeToscaName));
+ }
+
Resource genericTypeResource = findLatestGeneric.left().value();
component.setDerivedFromGenericInfo(genericTypeResource);
return Either.left(genericTypeResource);
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 5b6488d788..6dc83bfc2b 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
@@ -401,6 +401,15 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
}
componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
+
+
+ artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
+ if ( artStatus != StorageOperationStatus.OK){
+ log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
+
+ }
+ componentInstance.setArtifacts(originComponent.getArtifacts());
return Either.left(ActionStatus.OK);
}
@@ -1828,23 +1837,23 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
return result;
}
+
+ public Either<ComponentInstance, ResponseFormat> deleteServiceProxy(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
+ // TODO Add implementation
+ Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
+ return result;
+ }
- private Boolean validateInstanceNameUniqueness(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
- Boolean isUnique = true;
- String newInstanceNormalizedName = ValidationUtils.normalizeComponentInstanceName(newInstanceName);
- if (!oldComponentInstance.getNormalizedName().equals(newInstanceNormalizedName)) {
- Optional<ComponentInstance> foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(newInstanceNormalizedName)).findFirst();
- if (foundComponentInstance.isPresent()) {
- isUnique = false;
- }
- if (isUnique) {
- foundComponentInstance = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().endsWith(newInstanceNormalizedName)).findFirst();
- if (foundComponentInstance.isPresent()) {
- isUnique = false;
- }
- }
- }
- return isUnique;
+ public Either<ComponentInstance, ResponseFormat> createServiceProxy(String containerComponentType, String containerComponentId, String userId, ComponentInstance componentInstance) {
+ // TODO Add implementation
+ Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
+ return result;
+ }
+
+ public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion(String containerComponentType, String containerComponentId, String serviceProxyId, String userId) {
+ // TODO Add implementation
+ Either<ComponentInstance, ResponseFormat> result = Either.left(new ComponentInstance());
+ return result;
}
private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
@@ -1889,12 +1898,11 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
- if (StringUtils.isEmpty(resourceInstanceForUpdate.getName())) {
+ if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
-
}
- if (StringUtils.isEmpty(resourceInstanceForUpdate.getNormalizedName()))
- resourceInstanceForUpdate.setNormalizedName(origInstanceForUpdate.getNormalizedName());
+
+ resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java
index 3dee3839b1..2de9eee217 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupTypeImportManager.java
@@ -20,15 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Consumer;
-import java.util.stream.Collectors;
-
-import javax.annotation.Resource;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
@@ -37,16 +29,21 @@ import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.GroupTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
@Component("groupTypeImportManager")
public class GroupTypeImportManager {
@@ -69,13 +66,11 @@ public class GroupTypeImportManager {
private static Logger log = LoggerFactory.getLogger(GroupTypeImportManager.class.getName());
@Resource
- private PropertyOperation propertyOperation;
- @Resource
private IGroupTypeOperation groupTypeOperation;
@Resource
private ComponentsUtils componentsUtils;
@Resource
- private IResourceOperation resourceOperation;
+ private ToscaOperationFacade toscaOperationFacade;
@Resource
private CommonImportManager commonImportManager;
@@ -103,7 +98,7 @@ public class GroupTypeImportManager {
} else {
for (String member : groupType.getMembers()) {
// Verify that such Resource exist
- Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> eitherMemberExist = resourceOperation.getLatestByToscaResourceName(member, false);
+ Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> eitherMemberExist = toscaOperationFacade.getLatestByToscaResourceName(member);
if (eitherMemberExist.isRight()) {
StorageOperationStatus operationStatus = eitherMemberExist.right().value();
log.debug("Error when fetching parent resource {}, error: {}", member, operationStatus);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java
index 838cd53458..1755d0b20c 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java
@@ -21,12 +21,7 @@
package org.openecomp.sdc.be.components.impl;
import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import java.util.Map.Entry;
import java.util.function.Consumer;
import java.util.function.Function;
@@ -61,22 +56,55 @@ public final class ImportUtils {
private ImportUtils() {
}
- public static Yaml STRICT_MAPPING_YAML_LOADER = new YamlLoader().getStrictYamlLoader();
private static CustomResolver customResolver = new CustomResolver();
+ private static Yaml STRICT_MAPPING_YAML_LOADER = new YamlLoader().getStrictYamlLoader();
private static class CustomResolver extends Resolver {
- @Override
+ @Override
protected void addImplicitResolvers() {
- // avoid implicit resolvers for strings that can be interpreted as boolean values
- addImplicitResolver(Tag.STR, EMPTY, "");
- addImplicitResolver(Tag.STR, NULL, null);
- addImplicitResolver(Tag.NULL, NULL, "~nN\0");
- addImplicitResolver(Tag.NULL, EMPTY, null);
- addImplicitResolver(Tag.YAML, YAML, "!&*");
+ // avoid implicit resolvers for strings that can be interpreted as boolean values
+ addImplicitResolver(Tag.STR, EMPTY, "");
+ addImplicitResolver(Tag.STR, NULL, null);
+ addImplicitResolver(Tag.NULL, NULL, "~nN\0");
+ addImplicitResolver(Tag.NULL, EMPTY, null);
+ addImplicitResolver(Tag.INT, INT, "-+0123456789");
+ addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789.");
+ addImplicitResolver(Tag.YAML, YAML, "!&*");
}
}
-
+
+
+ private static void buildMap(Map<String, Object> output, Map<String, Object> map) {
+ for (Entry<String, Object> entry : map.entrySet()) {
+ String key = entry.getKey();
+ Object value = entry.getValue();
+ if (value instanceof Map) {
+ Map<String, Object> result = new LinkedHashMap<>();
+ buildMap(result, (Map) value);
+ output.put(key, result);
+ }
+ else if (value instanceof Collection) {
+ Map<String, Object> result = new LinkedHashMap<>();
+ int i = 0;
+ for(Object item : (Collection<Object>) value) {
+ buildMap(result, Collections.singletonMap("[" + (i++) + "]", item));
+ }
+ output.put(key, new ArrayList<>(result.values()));
+ }
+ else {
+ output.put(key, value);
+ }
+ }
+ }
+
+ public static Map<String, Object> loadYamlAsStrictMap(String content){
+ Map<String, Object> result = new LinkedHashMap<>();
+ Object map = STRICT_MAPPING_YAML_LOADER.load(content);
+ buildMap(result, (Map<String, Object>)map);
+ return result;
+ }
+
private static class YamlLoader extends YamlProcessor {
public Yaml getStrictYamlLoader() {
return createYaml();
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 f85e25e5fb..892da8af9d 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
@@ -1274,6 +1274,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
input.setName(inputName + "_" + prop.getName());
}
+ input.setDefaultValue(prop.getValue());
input.setName(inputName);
input.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(component.getUniqueId(), input.getName()));
input.setInputPath(propertiesName);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java
index 1e0670daa2..7b55a6988e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyTypeImportManager.java
@@ -20,41 +20,36 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Consumer;
-
-import javax.annotation.Resource;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.components.impl.CommonImportManager.ElementTypeEnum;
import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.PolicyTypeDefinition;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
import org.openecomp.sdc.be.model.operations.api.IPolicyTypeOperation;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
-import fj.data.Either;
+import javax.annotation.Resource;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Consumer;
@Component("policyTypeImportManager")
public class PolicyTypeImportManager {
@Resource
- private PropertyOperation propertyOperation;
- @Resource
private IPolicyTypeOperation policyTypeOperation;
@Resource
private ComponentsUtils componentsUtils;
- @Resource
- private IResourceOperation resourceOperation;
@Autowired
protected IGroupOperation groupOperation;
+ @Autowired
+ private ToscaOperationFacade toscaOperationFacade;
@Resource
private CommonImportManager commonImportManager;
@@ -82,7 +77,8 @@ public class PolicyTypeImportManager {
}
if (result.isLeft()) {
for (String targetName : policyType.getTargets()) {
- boolean isValid = resourceOperation.getLatestByToscaResourceName(targetName, false).isLeft();
+
+ boolean isValid = toscaOperationFacade.getLatestByToscaResourceName(targetName).isLeft();;
if (!isValid) {
isValid = groupOperation.isGroupExist(targetName, false);
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
index 96f7eec2d8..da64f3f5b7 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductBusinessLogic.java
@@ -43,7 +43,6 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ProductOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
index 7f73dc405c..833e6c0b9e 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PropertyBusinessLogic.java
@@ -20,16 +20,11 @@
package org.openecomp.sdc.be.components.impl;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.function.Supplier;
-
-import javax.servlet.ServletContext;
-
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonElement;
+import com.google.gson.reflect.TypeToken;
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -38,7 +33,6 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.IComplexDefaultValue;
@@ -46,12 +40,8 @@ import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
@@ -61,20 +51,20 @@ import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
import org.openecomp.sdc.be.resources.data.EntryData;
import org.openecomp.sdc.be.resources.data.PropertyData;
import org.openecomp.sdc.common.api.Constants;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonElement;
-import com.google.gson.reflect.TypeToken;
-
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.function.Supplier;
@Component("propertyBusinessLogic")
public class PropertyBusinessLogic extends BaseBusinessLogic {
@@ -87,9 +77,6 @@ public class PropertyBusinessLogic extends BaseBusinessLogic {
private DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance();
- @javax.annotation.Resource
- private IResourceOperation resourceOperation = null;
-
protected static IElementOperation getElementDao(Class<IElementOperation> class1, ServletContext context) {
WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java
index f8dde98010..bd7e810066 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/RequirementsBusinessLogic.java
@@ -20,23 +20,11 @@
package org.openecomp.sdc.be.components.impl;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
-import org.openecomp.sdc.common.config.EcompErrorName;
-import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
-import fj.data.Either;
-
@Component("requirementsBusinessLogic")
public class RequirementsBusinessLogic {
private static Logger log = LoggerFactory.getLogger(RequirementsBusinessLogic.class.getName());
@@ -47,48 +35,5 @@ public class RequirementsBusinessLogic {
@javax.annotation.Resource
private ResourceBusinessLogic resourceBusinessLogic;
- @javax.annotation.Resource
- private IResourceOperation resourceOperation;
-
- public Either<RequirementDefinition, ResponseFormat> updateRequirement(String resourceId, String requirementId, RequirementDefinition requirementDefinition, String userId) {
-
- // Get the resource from DB
- Either<Resource, StorageOperationStatus> status = getResource(resourceId);
- if (status.isRight()) {
- log.debug("Couldn't get resource {} from DB", resourceId);
- return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(status.right().value()), ""));
- }
- Resource resource = status.left().value();
- if (resource == null) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Requirement Business Logic", resourceId);
- BeEcompErrorManager.getInstance().logBeComponentMissingError("Requirement Business Logic", ComponentTypeEnum.RESOURCE.getValue(), resourceId);
- log.debug("Couldn't get resource {} from DB", resourceId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- // verify that resource is checked-out and the user is the last updater
- if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
- }
-
- // TODO
- return null;
- }
-
- private Either<Resource, StorageOperationStatus> getResource(final String resourceId) {
-
- log.debug("Get resource with id {}", resourceId);
- Either<Resource, StorageOperationStatus> status = resourceOperation.getResource(resourceId);
- if (status.isRight()) {
- log.debug("Resource with id {} was not found", resourceId);
- return Either.right(status.right().value());
- }
-
- Resource resource = status.left().value();
- if (resource == null) {
- log.debug("General Error while get resource with id {}", resourceId);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- return Either.left(resource);
- }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java
index 0aa4a6f006..383f1eb2ec 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java
@@ -154,6 +154,7 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import fj.data.Either;
+import org.yaml.snakeyaml.parser.ParserException;
@org.springframework.stereotype.Component("resourceBusinessLogic")
public class ResourceBusinessLogic extends ComponentBusinessLogic {
@@ -686,7 +687,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return result;
}
-
private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map<String, NodeTypeInfo> nodeTypesInfo, Map<String, byte[]> csar, String csarUUID, String yamlFileName, Resource oldResource, User user) {
Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar);
@@ -695,8 +695,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
try {
nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
- Map<String, String> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, yamlFileName, oldResource.getSystemName());
- Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes = null;
+ Map<String, String> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, yamlFileName, oldResource.getName());
+ Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes;
EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifactsToHandle = null;
log.debug("Going to fetch node types for resource with name {} during import csar with UUID {}. ", oldResource.getName(), csarUUID);
@@ -957,9 +957,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csar.left().value(), yamlFileContents);
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar.left().value(), resource);
CsarInfo csarInfo = new CsarInfo(resource.getName(), user, csarUUID, csar.left().value(), false);
- Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, yamlFileName, nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, true, false, null);
+ Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csarInfo.getCsar(), csarInfo.getCsarUUID(), yamlFileName, resource, csarInfo.getModifier());
+ if (findNodeTypesArtifactsToHandleRes.isRight()) {
+ log.debug("failed to find node types for update with artifacts during import csar {}. ", csarInfo.getCsarUUID());
+ return Either.right(findNodeTypesArtifactsToHandleRes.right().value());
+ }
+ Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, yamlFileName, nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, null);
if (createResourceFromYaml.isRight()) {
log.debug("Couldn't create resource from YAML");
return Either.right(createResourceFromYaml.right().value());
@@ -1216,14 +1220,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if(result == null){
newComplexVfc = buildCvfcRes.left().value();
- if(csarInfo.isUpdate()){
- Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade.getLatestByToscaResourceName(newComplexVfc.getToscaResourceName());
- if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND){
- log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- } else if(oldComplexVfcRes.isLeft()){
- oldComplexVfc = oldComplexVfcRes.left().value();
- }
+ Either<Resource, StorageOperationStatus> oldComplexVfcRes = toscaOperationFacade.getLatestByToscaResourceName(newComplexVfc.getToscaResourceName());
+ if(oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND){
+ log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value());
+ result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ } else if(oldComplexVfcRes.isLeft()){
+ oldComplexVfc = oldComplexVfcRes.left().value();
}
}
if(result == null){
@@ -1417,7 +1419,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
cvfc.setVendorName(resourceVf.getVendorName());
cvfc.setVendorRelease(resourceVf.getVendorRelease());
cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
- cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), csarInfo.getVfResourceName(), nodeName));
+ cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.CVFC.name(), csarInfo.getVfResourceName(), nodeName));
cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
List<String> tags = new ArrayList<>();
@@ -1889,18 +1891,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return result;
}
- private Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> findNodeTypeArtifactsToCreate(Map<String, byte[]> csar, Resource resource) {
-
- Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar);
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
- for (Map.Entry<String, List<ArtifactDefinition>> currArts : extractedVfcsArtifacts.entrySet()) {
- EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> artifactsToCreate = new EnumMap<>(ArtifactOperationEnum.class);
- artifactsToCreate.put(ArtifactOperationEnum.Create, currArts.getValue());
- nodeTypesArtifactsToHandle.put(currArts.getKey(), artifactsToCreate);
- }
- return nodeTypesArtifactsToHandle;
- }
-
private void handleAndAddExtractedVfcsArtifacts(List<ArtifactDefinition> vfcArtifacts, List<ArtifactDefinition> artifactsToAdd) {
List<String> vfcArtifactNames = vfcArtifacts.stream().map(a -> a.getArtifactName()).collect(Collectors.toList());
artifactsToAdd.stream().forEach(a -> {
@@ -3348,7 +3338,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
resStatus = Either.right(responseFormat);
return resStatus;
}
- currHeatParam.setCurrentValue(HeatParameterType.isValidType(currHeatParam.getType()).getConverter().convert(updatedParamValue, null, null));
+ currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
// newHeatEnvParams.add(currHeatParam);
break;
}
@@ -3558,6 +3548,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, List<ComponentInstanceProperty>> instProperties = new HashMap<>();
Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties = new HashMap<>();
Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instRequirements = new HashMap<>();
+ Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts = new HashMap<>();
Map<String, Map<String, ArtifactDefinition>> instArtifacts = new HashMap<>();
Map<String, List<PropertyDefinition>> instAttributes = new HashMap<>();
Map<String, Resource> originCompMap = new HashMap<>();
@@ -3566,10 +3557,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
+ log.trace("Processing entry: {}", entry);
UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
ComponentInstance currentCompInstance = null;
for (ComponentInstance compInstance : componentInstancesList) {
-
+ log.trace("Processing component instance: {}", compInstance);
if (compInstance.getName().equals(uploadComponentInstanceInfo.getName())) {
currentCompInstance = compInstance;
break;
@@ -3629,7 +3621,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
instRequirements.put(currentCompInstance, originRequirements);
}
if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty())
- instArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
+ instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
+ if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty())
+ instArtifacts.put(resourceInstanceId, originResource.getArtifacts());
if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty())
instAttributes.put(resourceInstanceId, originResource.getAttributes());
if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
@@ -3667,7 +3661,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
}
- StorageOperationStatus addArtToInst = toscaOperationFacade.associateArtifactToInstances(instArtifacts, resource.getUniqueId(), user);
+ StorageOperationStatus addArtToInst = toscaOperationFacade.associateDeploymentArtifactsToInstances(instDeploymentArtifacts, resource.getUniqueId(), user);
+ if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
+ log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
+ return Either.right(responseFormat);
+ }
+
+ addArtToInst = toscaOperationFacade.associateArtifactsToInstances(instArtifacts, resource.getUniqueId(), user);
if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) {
log.debug("failed to associate artifact of resource {} status is {}", resource.getUniqueId(), addArtToInst);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName);
@@ -4212,7 +4213,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate();
}
else {
- mappedToscaTemplate = (Map<String, Object>) new Yaml().load(resourceYml);
+ try {
+ //DE154502 Fail if duplicate key found in file
+ mappedToscaTemplate = ImportUtils.loadYamlAsStrictMap(resourceYml);
+
+ } catch(ParserException e) {
+ log.error("Failed to load yaml file {}", yamlFileName, e);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.TOSCA_PARSE_ERROR, yamlFileName, e.getMessage());
+ return Either.right(responseFormat);
+ }
}
Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
if (toscaElementEither.isRight()) {
@@ -5573,10 +5582,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// IResourceOperation dataModel = getResourceOperation();
Either<Resource, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(resourceId);
-
if (storageStatus.isRight()) {
log.debug("failed to get resource by id {}", resourceId);
- return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), ""));
+ return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(storageStatus.right().value()), resourceId));
+ }
+ if(!(storageStatus.left().value() instanceof Resource)){
+ return Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), resourceId));
}
return Either.left(storageStatus.left().value());
@@ -6807,14 +6818,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
try {
if (groupTemplateJson != null && groupTemplateJson instanceof Map) {
Map<String, Object> groupTemplateJsonMap = (Map<String, Object>) groupTemplateJson;
- // Type
- String groupType = null;
- if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
+ String groupType = (String) groupTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
+ if (!StringUtils.isEmpty(groupType)) {
groupInfo.setType(groupType);
} else {
log.debug("The 'type' member is not found under group {}", groupName);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupName));
}
if (groupTemplateJsonMap.containsKey(ToscaTagNamesEnum.DESCRIPTION.getElementName())) {
@@ -6832,8 +6841,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
groupInfo.setMembers(membersLoaded);
} else {
- log.debug("The 'type' member is not found under group {}", groupName);
- result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
+ log.debug("The 'members' member is not of type list under group {}", groupName);
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
}
}
}
@@ -6873,7 +6882,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = groupTypeOperation.getLatestGroupTypeByType(groupType, true);
if (groupTypeRes.isRight()) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_MISSING_GROUP_TYPE, groupType));
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GROUP_TYPE_IS_INVALID, groupType));
}
Map<String, PropertyDefinition> gtProperties = new HashMap<>();
@@ -7067,6 +7076,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
private String buildNestedToscaResourceName(String nodeResourceType, String vfResourceName, String nodeTypeFullName) {
+ String actualType;
+ String actualVfName;
+ if(ResourceTypeEnum.CVFC.name().equals(nodeResourceType)){
+ actualVfName = vfResourceName + ResourceTypeEnum.CVFC.name();
+ actualType = ResourceTypeEnum.VFC.name();
+ } else {
+ actualVfName = vfResourceName;
+ actualType = nodeResourceType;
+ }
StringBuilder toscaResourceName = new StringBuilder(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX);
String nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
String[] findTypes = nameWithouNamespacePrefix.split("\\.");
@@ -7074,9 +7092,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
if (actualName.startsWith(Constants.ABSTRACT)) {
- toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(vfResourceName));
+ toscaResourceName.append(resourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName));
} else {
- toscaResourceName.append(nodeResourceType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(vfResourceName)).append('.').append(Constants.ABSTRACT);
+ toscaResourceName.append(actualType.toLowerCase()).append('.').append(ValidationUtils.convertToSystemName(actualVfName)).append('.').append(Constants.ABSTRACT);
}
return toscaResourceName.append(actualName.toLowerCase()).toString();
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java
index ac6183db00..b21195ff42 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java
@@ -20,22 +20,7 @@
package org.openecomp.sdc.be.components.impl;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-import javax.servlet.ServletContext;
-
+import fj.data.Either;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.auditing.api.IAuditingManager;
@@ -53,24 +38,13 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.CsarInfo;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.UploadResourceInfo;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
@@ -83,7 +57,20 @@ import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.yaml.snakeyaml.Yaml;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
@Component("resourceImportManager")
public class ResourceImportManager {
@@ -102,9 +89,6 @@ public class ResourceImportManager {
@Autowired
protected ComponentsUtils componentsUtils;
- @Autowired
- protected ResourceOperation resourceOperation;
-
public final static Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern
.compile("[\\w\\-\\_\\d\\:]+");
@Autowired
@@ -963,8 +947,5 @@ public class ResourceImportManager {
this.auditingManager = auditingManager;
}
- public void setResourceOperation(ResourceOperation resourceOperation) {
- this.resourceOperation = resourceOperation;
- }
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java
index ae7ae31ed9..85db9a2c0f 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
@@ -1144,17 +1144,22 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (eitherCreator.isRight()) {
return Either.right(eitherCreator.right().value());
}
- user = eitherCreator.left().value();
Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
if (storageStatus.isRight()) {
log.debug("failed to get service by id {}", serviceId);
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), serviceId));
}
- // Service service =
- // createServiceApiArtifactLIst(storageStatus.left().value());
+
+ if(!(storageStatus.left().value() instanceof Service)){
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.NOT_FOUND), serviceId));
+ }
Service service = storageStatus.left().value();
return Either.left(service);
+
+
+
+
}
public Either<Service, ResponseFormat> getServiceByNameAndVersion(String serviceName, String serviceVersion, String userId) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java
index 11ffcd9329..d1cc93acc8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceComponentInstanceBusinessLogic.java
@@ -22,12 +22,8 @@ package org.openecomp.sdc.be.components.impl;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
-import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.stereotype.Component;
-import fj.data.Either;
-
@Component("serviceComponentInstanceBusinessLogic")
public class ServiceComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java
index b18c4d0985..d12afdbd55 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java
@@ -20,18 +20,8 @@
package org.openecomp.sdc.be.components.lifecycle;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-
-import org.apache.commons.codec.binary.Base64;
+import fj.data.Either;
import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -42,40 +32,30 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
-import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
-import org.openecomp.sdc.be.tosca.ToscaError;
import org.openecomp.sdc.be.tosca.ToscaExportHandler;
-import org.openecomp.sdc.be.tosca.ToscaRepresentation;
-import org.openecomp.sdc.be.tosca.ToscaUtils;
import org.openecomp.sdc.be.user.Role;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+import java.util.Set;
public class CertificationRequestTransition extends LifeCycleTransition {
@@ -326,47 +306,6 @@ public class CertificationRequestTransition extends LifeCycleTransition {
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> parseRelationsForReqCapVerification(Component component, Map<String, List<String>> reqName2Ids, Map<String, List<String>> capName2Ids) {
- log.debug("Submit for testing validation - Preparing relations for inner atomic instances validation");
- List<RequirementCapabilityRelDef> componentInstancesRelations = component.getComponentInstancesRelations();
- if (componentInstancesRelations != null) {
- for (RequirementCapabilityRelDef reqCapRelDef : componentInstancesRelations) {
- List<RequirementAndRelationshipPair> relationships = reqCapRelDef.getRelationships();
- if (relationships != null) {
- for (RequirementAndRelationshipPair reqRelPair : relationships) {
- String capUniqueId = reqRelPair.getCapabilityUid();
- Either<CapabilityDefinition, StorageOperationStatus> capability = capabilityOperation.getCapability(capUniqueId);
- if (capability.isRight()) {
- log.error("Couldn't fetch capability by id {}", capUniqueId);
- return Either.right(componentUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
- }
- String reqCapType = capability.left().value().getType();
- String capabilityOwnerId = reqRelPair.getCapabilityOwnerId();
- String requirementOwnerId = reqRelPair.getRequirementOwnerId();
- // Update req
- List<String> reqIds = reqName2Ids.get(reqCapType);
- if (reqIds == null) {
- reqIds = new ArrayList<>();
- reqName2Ids.put(reqCapType, reqIds);
- }
- reqIds.add(requirementOwnerId);
- // Update cap
- List<String> capIds = capName2Ids.get(reqCapType);
- if (capIds == null) {
- capIds = new ArrayList<>();
- capName2Ids.put(reqCapType, capIds);
- }
- capIds.add(capabilityOwnerId);
- }
- }
- }
- log.debug("Parsed req for validation: {}, parsed cap for validation: {}", reqName2Ids, capName2Ids);
- } else {
- log.debug("There are no relations found for component {}", component.getUniqueId());
- }
- return Either.left(true);
- }
-
@Override
public Either<Boolean, ResponseFormat> validateBeforeTransition(Component component, ComponentTypeEnum componentType, User modifier, User owner, LifecycleStateEnum oldState, LifecycleChangeInfoWithAction lifecycleChangeInfo) {
String componentName = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java
index 0d0e06fe6d..cc534bb694 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifeCycleTransition.java
@@ -39,7 +39,6 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.Role;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java
index 8a80e0bb64..24266521c2 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/StartCertificationTransition.java
@@ -20,15 +20,12 @@
package org.openecomp.sdc.be.components.lifecycle;
-import java.util.Arrays;
-
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
+import fj.data.Either;
import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.Component;
@@ -39,7 +36,6 @@ import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
-import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.Role;
@@ -47,7 +43,7 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import fj.data.Either;
+import java.util.Arrays;
public class StartCertificationTransition extends LifeCycleTransition {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java
index 436b2319e9..fa31989d87 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java
@@ -20,19 +20,9 @@
package org.openecomp.sdc.be.listen;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.jar.Attributes;
-import java.util.jar.Manifest;
-
-import javax.servlet.ServletContext;
-import javax.servlet.ServletContextEvent;
-import javax.servlet.ServletContextListener;
-
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.impl.DownloadArtifactLogic;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
import org.openecomp.sdc.be.monitoring.BeMonitoringService;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
@@ -41,6 +31,14 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
public class BEAppContextListener extends AppContextListener implements ServletContextListener {
private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF";
@@ -71,11 +69,6 @@ public class BEAppContextListener extends AppContextListener implements ServletC
}
- private IResourceOperation getResourceOperationManager(Class<? extends IResourceOperation> clazz, WebApplicationContext webContext) {
-
- return webContext.getBean(clazz);
- }
-
private String getVersionFromManifest(ServletContextEvent context) {
ServletContext servletContext = context.getServletContext();
InputStream inputStream = servletContext.getResourceAsStream(MANIFEST_FILE_NAME);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java b/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java
index 34a56cdd13..6be300d6db 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/monitoring/EsGateway.java
@@ -74,7 +74,8 @@ public class EsGateway extends ProxyServlet {
esPort = monitoringBL.getEsPort();
}
- String scheme = request.getScheme();
+ //String scheme = request.getScheme(); esGateway HTTP
+ String scheme = "http";
String contextPath = request.getContextPath(); // /mywebapp
String servletPath = request.getServletPath(); // /servlet/MyServlet
String pathInfo = request.getPathInfo(); // /a/b;c=123
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java
index d7db4ec3a3..a89d8b109b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java
@@ -880,6 +880,120 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet {
}
+ @POST
+ @Path("/{containerComponentType}/{containerComponentId}/serviceProxy")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Create service proxy", httpMethod = "POST", notes = "Returns created service proxy", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
+ @ApiResponse(code = 409, message = "Service proxy already exist") })
+ public Response createServiceProxy(@ApiParam(value = "RI object to be created", required = true) String data, @PathParam("containerComponentId") final String containerComponentId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+
+ try {
+
+ ComponentInstance componentInstance = RepresentationUtils.fromRepresentation(data, ComponentInstance.class);
+ componentInstance.setInvariantName(null);
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ if(componentTypeEnum != ComponentTypeEnum.SERVICE){
+ log.debug("Unsupported container component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+ Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.createServiceProxy(containerComponentType, containerComponentId, userId, componentInstance);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.CREATED), actionResponse.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create service proxy");
+ log.debug("Create service proxy failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @DELETE
+ @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Delete service proxy", httpMethod = "DELETE", notes = "Returns delete service proxy", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response deleteServiceProxy(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId,
+ @ApiParam(value = "valid values: resources / services / products", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME + ","
+ + ComponentTypeEnum.PRODUCT_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+ String url = request.getMethod() + " " + request.getRequestURI();
+ Response response = null;
+ try {
+ log.debug("Start handle request of {}", url);
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+ Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.deleteServiceProxy(containerComponentType, containerComponentId, serviceProxyId, userId);
+
+ if (actionResponse.isRight()) {
+ response = buildErrorResponse(actionResponse.right().value());
+ } else {
+ response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null);
+ }
+ return response;
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete service proxy");
+ log.debug("Delete service proxy failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
+ @POST
+ @Path("/{containerComponentType}/{containerComponentId}/serviceProxy/{serviceProxyId}/changeVersion/{newServiceId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(value = "Update service proxy with new version", httpMethod = "POST", notes = "Returns updated service proxy", response = Response.class)
+ @ApiResponses(value = { @ApiResponse(code = 201, message = "Service proxy created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
+ public Response changeServiceProxyVersion(@PathParam("containerComponentId") final String containerComponentId, @PathParam("serviceProxyId") final String serviceProxyId,
+ @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
+ @Context final HttpServletRequest request) {
+ ServletContext context = request.getSession().getServletContext();
+
+ String url = request.getMethod() + " " + request.getRequestURI();
+ log.debug("Start handle request of {}", url);
+ try {
+
+ String userId = request.getHeader(Constants.USER_ID_HEADER);
+
+ ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
+ ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context, componentTypeEnum);
+ if (componentInstanceLogic == null) {
+ log.debug("Unsupported component type {}", containerComponentType);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType));
+ }
+ Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceLogic.changeServiceProxyVersion(containerComponentType, containerComponentId, serviceProxyId, userId);
+
+ if (actionResponse.isRight()) {
+ return buildErrorResponse(actionResponse.right().value());
+ }
+ return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value());
+
+ } catch (Exception e) {
+ BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update service proxy with new version");
+ log.debug("Update service proxy with new version failed with exception", e);
+ return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ }
+
private Either<ComponentInstance, ResponseFormat> convertToResourceInstance(String data) {
// Either<ComponentInstance, ActionStatus> convertStatus =
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java
index 22943bccea..2e961f294b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/TypesFetchServlet.java
@@ -20,6 +20,7 @@
package org.openecomp.sdc.be.servlets;
+import java.lang.reflect.Type;
import java.util.Map;
import javax.inject.Singleton;
@@ -39,7 +40,9 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyConstraint;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintSerialiser;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.datastructure.Wrapper;
@@ -48,6 +51,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.reflect.TypeToken;
import com.jcabi.aspects.Loggable;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@@ -95,9 +101,12 @@ public class TypesFetchServlet extends AbstractValidationsServlet {
// return buildErrorResponse(allDataTypes.right().value());
} else {
+
Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
- Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypes);
+ String dataTypeJson = gson.toJson(dataTypes);
+ Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
responseWrapper.setInnerElement(okResponse);
+
}
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java
index 3fd5297439..6c4c5fafe1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java
@@ -122,7 +122,7 @@ public class CapabiltyRequirementConvertor {
if (prop.getSchema() != null && prop.getSchema().getProperty() != null) {
innerType = prop.getSchema().getProperty().getType();
}
- Object convertedValue = PropertyConvertor.getInstance().convertToToscaObject(propertyType, prop.getName(), prop.getValue(), innerType, dataTypes);
+ Object convertedValue = PropertyConvertor.getInstance().convertToToscaObject(propertyType, prop.getValue(), innerType, dataTypes);
return convertedValue;
}
@@ -183,9 +183,19 @@ public class CapabiltyRequirementConvertor {
if (requirements != null) {
for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
entry.getValue().stream().forEach(r -> {
- String fullReqName = getRequirementPath(r);
+ String fullReqName;
+ String sourceCapName;
+ if(ToscaUtils.isComplexVfc(component)){
+ fullReqName = r.getName();
+ sourceCapName = getSourceCvfcDataTypeName(r.getName(), r.getOwnerName());
+ } else {
+ fullReqName = getRequirementPath(r);
+ sourceCapName = getSubPathByFirstDelimiterAppearance(fullReqName);
+ }
log.debug("the requirement {} belongs to resource {} ", fullReqName, component.getUniqueId());
- toscaRequirements.put(fullReqName, new String[]{r.getOwnerName(), getSubPathByFirstDelimiterAppearance(fullReqName)});
+ if(sourceCapName!= null){
+ toscaRequirements.put(fullReqName, new String[]{r.getOwnerName(), sourceCapName});
+ }
});
log.debug("Finish convert Requirements for node type");
}
@@ -195,6 +205,13 @@ public class CapabiltyRequirementConvertor {
return toscaRequirements;
}
+ private String getSourceCvfcDataTypeName(String name, String ownerName) {
+ if(name.contains(ownerName)){
+ return name.substring(0, name.length() - ownerName.length() - 1);
+ }
+ return null;
+ }
+
private String getRequirementPath(RequirementDefinition r) {
List<String> pathArray = Lists.reverse(r.getPath().stream()
.map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path)))
@@ -254,9 +271,19 @@ public class CapabiltyRequirementConvertor {
if (capabilities != null) {
for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
entry.getValue().stream().forEach(c -> {
- String fullCapName = getCapabilityPath(c);
+ String fullCapName;
+ String sourceReqName;
+ if(ToscaUtils.isComplexVfc(component)){
+ fullCapName = c.getName();
+ sourceReqName = getSourceCvfcDataTypeName(c.getName(), c.getOwnerName());
+ } else {
+ fullCapName = getCapabilityPath(c);
+ sourceReqName = getSubPathByFirstDelimiterAppearance(fullCapName);
+ }
log.debug("the capabilty {} belongs to resource {} ", fullCapName, component.getUniqueId());
- toscaCapabilities.put(fullCapName, new String[]{c.getOwnerName(), getSubPathByFirstDelimiterAppearance(fullCapName)});
+ if(sourceReqName!= null){
+ toscaCapabilities.put(fullCapName, new String[]{c.getOwnerName(), sourceReqName});
+ }
});
}
} else {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java
index b70dae68e8..85b1927548 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java
@@ -20,26 +20,8 @@
package org.openecomp.sdc.be.tosca;
-import java.io.BufferedOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-import java.util.zip.ZipOutputStream;
-
+import com.google.gson.Gson;
+import fj.data.Either;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
@@ -68,10 +50,10 @@ import org.openecomp.sdc.be.model.Operation;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
-import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData;
import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
@@ -92,9 +74,25 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import com.google.gson.Gson;
-
-import fj.data.Either;
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
/**
@@ -814,10 +812,10 @@ public class CsarUtils {
if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) {
version = component.getVersion();
} else {
- String[] versionParts = component.getVersion().split(LifecycleOperation.VERSION_DELIMETER_REGEXP);
+ String[] versionParts = component.getVersion().split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP);
Integer majorVersion = Integer.parseInt(versionParts[0]);
- version = (majorVersion + 1) + LifecycleOperation.VERSION_DELIMETER + "0";
+ version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0";
}
additionalParams.put(AdditionalParams.ServiceVersion.getName(), version);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java
index b8414367aa..646a7ecc8b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java
@@ -20,12 +20,11 @@
package org.openecomp.sdc.be.tosca;
-import java.io.StringReader;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
+import com.google.gson.stream.JsonReader;
+import fj.data.Either;
import org.apache.commons.lang3.StringUtils;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.model.Component;
@@ -33,6 +32,7 @@ import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
+import org.openecomp.sdc.be.model.tosca.converters.DataTypePropertyConverter;
import org.openecomp.sdc.be.model.tosca.converters.ToscaMapValueConverter;
import org.openecomp.sdc.be.model.tosca.converters.ToscaValueConverter;
import org.openecomp.sdc.be.tosca.model.EntrySchema;
@@ -41,14 +41,10 @@ import org.openecomp.sdc.be.tosca.model.ToscaProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.gson.Gson;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonSyntaxException;
-import com.google.gson.stream.JsonReader;
-
-import fj.data.Either;
+import java.io.StringReader;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
public class PropertyConvertor {
private static PropertyConvertor instance;
@@ -101,7 +97,7 @@ public class PropertyConvertor {
prop.setEntry_schema(eschema);
}
log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(), property.getDefaultValue());
- prop.setDefaultp(convertToToscaObject(property.getType(), property.getName(), property.getDefaultValue(), innerType, dataTypes));
+ prop.setDefaultp(convertToToscaObject(property.getType(), property.getDefaultValue(), innerType, dataTypes));
prop.setType(property.getType());
prop.setDescription(property.getDescription());
if (isCapabiltyProperty) {
@@ -111,10 +107,10 @@ public class PropertyConvertor {
return prop;
}
- public Object convertToToscaObject(String propertyType, String propertyName, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
+ public Object convertToToscaObject(String propertyType, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType);
- if (value == null) {
- value = getDataTypeDefaultValue(propertyName, dataTypes.get(propertyType));
+ if (StringUtils.isEmpty(value)) {
+ value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes);
if(StringUtils.isEmpty(value)){
return null;
}
@@ -193,35 +189,4 @@ public class PropertyConvertor {
}
- private String getDataTypeDefaultValue(String propertyName, DataTypeDefinition dataTypeDefinition) {
-
- String delaultValue = null;
- JsonObject asJsonObjectIn = new JsonObject();
- Map<String, PropertyDefinition> allParentsProps = new HashMap<>();
- while (dataTypeDefinition != null) {
-
- List<PropertyDefinition> currentParentsProps = dataTypeDefinition.getProperties();
- if (currentParentsProps != null) {
- currentParentsProps.stream().forEach(p -> allParentsProps.put(p.getName(), p));
- }
-
- dataTypeDefinition = dataTypeDefinition.getDerivedFrom();
- }
- for (Entry<String, PropertyDefinition> entry : allParentsProps.entrySet()) {
- String propName = entry.getKey();
- PropertyDefinition propertyDefinition = entry.getValue();
- JsonElement elementValue = asJsonObjectIn.get(propName);
- if(elementValue == null && propertyDefinition.getDefaultValue() != null){
- JsonReader jsonReader = new JsonReader(new StringReader(propertyDefinition.getDefaultValue()));
- jsonReader.setLenient(true);
- elementValue = jsonParser.parse(jsonReader);
- asJsonObjectIn.add(propName, elementValue);
- }
- }
- if(!asJsonObjectIn.isJsonNull()){
- delaultValue = gson.toJson(asJsonObjectIn);
- }
- return delaultValue;
- }
-
}
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 f802d0f412..8e0c312f1a 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
@@ -634,7 +634,8 @@ public class ToscaExportHandler {
List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId);
if (instanceInputsList != null) {
instanceInputsList.forEach(input -> {
- Supplier<String> supplier = () -> input.getValue();
+
+ Supplier<String> supplier = () -> input.getValue() != null && !input.getValue().isEmpty()? input.getValue(): input.getDefaultValue();
convertAndAddValue(dataTypes, componentInstance, props, input, supplier);
});
}
@@ -695,7 +696,7 @@ public class ToscaExportHandler {
if (input.getSchema() != null && input.getSchema().getProperty() != null) {
innerType = input.getSchema().getProperty().getType();
}
- return propertyConvertor.convertToToscaObject(propertyType, input.getName(), supplier.get(), innerType, dataTypes);
+ return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, dataTypes);
}
private ToscaGroupTemplate convertGroup(GroupDefinition group) {
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 dce3b3bbc0..24586d9ea0 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
@@ -44,6 +44,16 @@ public class ToscaUtils {
}
return false;
}
+
+ public static boolean isComplexVfc(Component component) {
+ if (ComponentTypeEnum.RESOURCE == component.getComponentType()) {
+ ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType();
+ if (ResourceTypeEnum.CVFC == resourceType) {
+ return true;
+ }
+ }
+ return false;
+ }
public static Map<String, Object> objectToMap(Object objectToConvert, Class clazz) throws IllegalArgumentException, IllegalAccessException {
Map<String, Object> map = new HashMap<>();
diff --git a/catalog-be/src/main/webapp/WEB-INF/web.xml b/catalog-be/src/main/webapp/WEB-INF/web.xml
index 889b1fac60..16c6fd6756 100644
--- a/catalog-be/src/main/webapp/WEB-INF/web.xml
+++ b/catalog-be/src/main/webapp/WEB-INF/web.xml
@@ -158,7 +158,7 @@
<url-pattern>/lbClassicStatus</url-pattern>
</servlet-mapping>
- <filter>
+<!-- <filter>
<filter-name>GzipFilter</filter-name>
<filter-class>org.eclipse.jetty.servlets.GzipFilter</filter-class>
<async-supported>true</async-supported>
@@ -175,7 +175,7 @@
<filter-name>GzipFilter</filter-name>
<url-pattern>/sdc2/rest/*</url-pattern>
</filter-mapping>
-
+-->
<context-param>
<param-name>contextConfigLocation</param-name>
@@ -190,9 +190,6 @@
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
-
-
-
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java
index 134038abb6..0dceaed4f2 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/GroupBusinessLogicTest.java
@@ -95,7 +95,7 @@ public class GroupBusinessLogicTest {
@BeforeClass
public static void setupBeforeClass() {
when(graphLockOperation.lockComponent(componentId, ComponentTypeEnum.RESOURCE.getNodeType())).thenReturn(StorageOperationStatus.OK);
- when(groupOperation.getGroup(groupUniqueId)).thenReturn(Either.left(groupDefenition));
+// when(groupOperation.getGroup(groupUniqueId)).thenReturn(Either.left(groupDefenition));
}
public enum ResponseEnum{
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java
index ae929edb31..1309af8ff7 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/PropertyBusinessLogicTest.java
@@ -41,7 +41,6 @@ import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.EntryData;
import org.openecomp.sdc.be.user.Role;
@@ -74,8 +73,6 @@ public class PropertyBusinessLogicTest {
@Mock
private IPropertyOperation propertyOperation;
@Mock
- private IResourceOperation resourceOperation;
- @Mock
private WebAppContextWrapper webAppContextWrapper;
@Mock
private UserBusinessLogic mockUserAdmin;
@@ -115,20 +112,20 @@ public class PropertyBusinessLogicTest {
when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
when(servletContext.getAttribute(Constants.PROPERTY_OPERATION_MANAGER)).thenReturn(propertyOperation);
when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
- when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation);
+// when(servletContext.getAttribute(Constants.RESOURCE_OPERATION_MANAGER)).thenReturn(resourceOperation);
when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
// Resource Operation mock methods
// getCount
- Either<Integer, StorageOperationStatus> eitherCount = Either.left(0);
- when(resourceOperation.getNumberOfResourcesByName("MyResourceName".toLowerCase())).thenReturn(eitherCount);
- Either<Integer, StorageOperationStatus> eitherCountExist = Either.left(1);
- when(resourceOperation.getNumberOfResourcesByName("alreadyExist".toLowerCase())).thenReturn(eitherCountExist);
- Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1);
- when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot);
-
- Either<Resource, StorageOperationStatus> eitherGetResource = Either.left(createResourceObject(true));
- when(resourceOperation.getResource(resourceId)).thenReturn(eitherGetResource);
+// Either<Integer, StorageOperationStatus> eitherCount = Either.left(0);
+// when(resourceOperation.getNumberOfResourcesByName("MyResourceName".toLowerCase())).thenReturn(eitherCount);
+// Either<Integer, StorageOperationStatus> eitherCountExist = Either.left(1);
+// when(resourceOperation.getNumberOfResourcesByName("alreadyExist".toLowerCase())).thenReturn(eitherCountExist);
+// Either<Integer, StorageOperationStatus> eitherCountRoot = Either.left(1);
+// when(resourceOperation.getNumberOfResourcesByName("Root".toLowerCase())).thenReturn(eitherCountRoot);
+//
+// Either<Resource, StorageOperationStatus> eitherGetResource = Either.left(createResourceObject(true));
+// when(resourceOperation.getResource(resourceId)).thenReturn(eitherGetResource);
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java
index a453df2563..c545474f5d 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java
@@ -55,7 +55,6 @@ import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.UploadResourceInfo;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.model.tosca.constraints.GreaterOrEqualConstraint;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.UserBusinessLogic;
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java
index ed16ca722a..d8b82da396 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/ServiceBusinessLogicTest.java
@@ -20,26 +20,12 @@
package org.openecomp.sdc.be.components;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.ServletContext;
-
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import org.openecomp.sdc.ElementOperationMock;
import org.openecomp.sdc.be.auditing.api.IAuditingManager;
import org.openecomp.sdc.be.auditing.impl.AuditingManager;
@@ -49,20 +35,15 @@ import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
-import org.openecomp.sdc.be.dao.impl.AuditingDao;
import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
@@ -72,8 +53,6 @@ import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CacheMangerOperation;
import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
-import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
@@ -83,7 +62,6 @@ import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ConfigurationSource;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
-import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent;
import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.common.util.ValidationUtils;
@@ -92,10 +70,15 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
+import javax.servlet.ServletContext;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
-import fj.data.Either;
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.when;
public class ServiceBusinessLogicTest {
@@ -158,7 +141,7 @@ public class ServiceBusinessLogicTest {
// Servlet Context attributes
when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
- when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation());
+// when(servletContext.getAttribute(Constants.SERVICE_OPERATION_MANAGER)).thenReturn(new ServiceOperation());
when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java
index 6cb90d0920..5de6762bdd 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ArtifactBusinessLogicTest.java
@@ -20,18 +20,10 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.cassandra.io.sstable.Component;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonElement;
+import fj.data.Either;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;
@@ -40,11 +32,8 @@ import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.InjectMocks;
-import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.openecomp.sdc.be.components.ArtifactsResolver;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
@@ -66,7 +55,6 @@ import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
import org.openecomp.sdc.be.resources.data.ESArtifactData;
import org.openecomp.sdc.be.servlets.RepresentationUtils;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
@@ -76,11 +64,14 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.exception.ResponseFormat;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonElement;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
-import fj.data.Either;
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.when;
public class ArtifactBusinessLogicTest {
@@ -95,7 +86,6 @@ public class ArtifactBusinessLogicTest {
public static final IInterfaceLifecycleOperation lifecycleOperation = Mockito.mock(IInterfaceLifecycleOperation.class);
public static final IUserAdminOperation userOperation = Mockito.mock(IUserAdminOperation.class);
public static final IElementOperation elementOperation = Mockito.mock(IElementOperation.class);
- public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class);
public static final ArtifactCassandraDao artifactCassandraDao = Mockito.mock(ArtifactCassandraDao.class);
public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
@@ -110,7 +100,7 @@ public class ArtifactBusinessLogicTest {
public static void setup() {
Either<ArtifactDefinition, StorageOperationStatus> NotFoundResult = Either.right(StorageOperationStatus.NOT_FOUND);
- when(artifactOperation.getArtifactById(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(NotFoundResult);
+// when(artifactOperation.getArtifactById(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(NotFoundResult);
Either<Map<String, ArtifactDefinition>, StorageOperationStatus> NotFoundResult2 = Either.right(StorageOperationStatus.NOT_FOUND);
when(artifactOperation.getArtifacts(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service), Mockito.anyBoolean())).thenReturn(NotFoundResult2);
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java
index d7b0800e03..a3022330a1 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceInstanceBusinessLogicTest.java
@@ -20,25 +20,12 @@
package org.openecomp.sdc.be.components.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
-import org.openecomp.sdc.be.components.impl.ServiceComponentInstanceBusinessLogic;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
@@ -55,7 +42,6 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.user.UserBusinessLogic;
@@ -66,7 +52,13 @@ import org.openecomp.sdc.common.impl.ExternalConfiguration;
import org.openecomp.sdc.common.impl.FSConfigurationSource;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.*;
public class ResourceInstanceBusinessLogicTest {
@@ -87,7 +79,7 @@ public class ResourceInstanceBusinessLogicTest {
public static final ArtifactsBusinessLogic artifactBusinessLogic = Mockito.mock(ArtifactsBusinessLogic.class);
public static final UserBusinessLogic userAdminManager = Mockito.mock(UserBusinessLogic.class);
- public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class);
+// public static final ServiceOperation serviceOperation = Mockito.mock(ServiceOperation.class);
public static final ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class);
public static final IGroupInstanceOperation groupInstanceOperation = Mockito.mock(IGroupInstanceOperation.class);
public static final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
@@ -132,7 +124,7 @@ public class ResourceInstanceBusinessLogicTest {
Object lightService = new Service();
Either<Object, StorageOperationStatus> eitherLightService = Either.left(lightService);
- Mockito.when(serviceOperation.getLightComponent(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherLightService);
+// Mockito.when(serviceOperation.getLightComponent(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(eitherLightService);
Mockito.doNothing().when(componentsUtils).auditComponent(Mockito.any(ResponseFormat.class), Mockito.any(User.class), Mockito.any(Component.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(AuditingActionEnum.class),
Mockito.any(ComponentTypeEnum.class), Mockito.any(EnumMap.class));
@@ -149,6 +141,7 @@ public class ResourceInstanceBusinessLogicTest {
StorageOperationStatus status = StorageOperationStatus.OK;
Mockito.when(toscaOperationFacade.addDeploymentArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any(Map.class))).thenReturn(status);
+ Mockito.when(toscaOperationFacade.addInformationalArtifactsToInstance(Mockito.any(String.class), Mockito.any(ComponentInstance.class), Mockito.any(Map.class))).thenReturn(status);
Mockito.when(toscaOperationFacade.addGroupInstancesToComponentInstance(Mockito.any(Component.class), Mockito.any(ComponentInstance.class), Mockito.any(List.class), Mockito.any(Map.class))).thenReturn(status);
}
@@ -156,7 +149,7 @@ public class ResourceInstanceBusinessLogicTest {
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
- Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager);
+// Mockito.reset(artifactBusinessLogic, serviceOperation, componentsUtils, userAdminManager);
setup();
}
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java
index e26934bfaf..6bfd64be41 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTest.java
@@ -20,13 +20,7 @@
package org.openecomp.sdc.be.components.lifecycle;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-import java.util.List;
-
+import fj.data.Either;
import org.apache.http.HttpStatus;
import org.junit.Before;
import org.junit.Test;
@@ -36,9 +30,7 @@ import org.mockito.MockitoAnnotations;
import org.openecomp.sdc.be.components.distribution.engine.ServiceDistributionArtifactsBuilder;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.Component;
@@ -49,18 +41,21 @@ import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
-import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
import org.openecomp.sdc.be.tosca.ToscaError;
import org.openecomp.sdc.be.tosca.ToscaExportHandler;
import org.openecomp.sdc.be.tosca.ToscaRepresentation;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.exception.ResponseFormat;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
public class CertificationRequestTest extends LifecycleTestBase {
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java
index 1488f13015..ff5c618138 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java
@@ -55,7 +55,6 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaElementLifecycleOper
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.user.Role;
import org.openecomp.sdc.be.user.UserBusinessLogic;
diff --git a/catalog-fe/src/main/webapp/WEB-INF/web.xml b/catalog-fe/src/main/webapp/WEB-INF/web.xml
index 725c041c51..b217cc0bf4 100644
--- a/catalog-fe/src/main/webapp/WEB-INF/web.xml
+++ b/catalog-fe/src/main/webapp/WEB-INF/web.xml
@@ -80,7 +80,7 @@
</servlet-mapping>
- <filter>
+<!-- <filter>
<filter-name>GzipFilter</filter-name>
<filter-class>org.eclipse.jetty.servlets.GzipFilter</filter-class>
<async-supported>true</async-supported>
@@ -103,14 +103,12 @@
<filter-name>GzipFilter</filter-name>
<url-pattern>/sdc1/*</url-pattern>
</filter-mapping>
-
-
-
+ -->
+
<filter>
<filter-name>gzipFilter</filter-name>
<filter-class>org.openecomp.sdc.fe.GzipFilter</filter-class>
</filter>
-
<filter-mapping>
<filter-name>gzipFilter</filter-name>
<url-pattern>*.jsgz</url-pattern>
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java
index c1fb2e0a7f..198325b6b5 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java
@@ -26,7 +26,6 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.cache.DaoInfo;
-import org.openecomp.sdc.be.model.operations.api.IComponentOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
import org.slf4j.Logger;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java
index b8d8cb39de..07c2f8d51c 100644
--- 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
@@ -269,6 +269,8 @@ public class ArtifactsOperations extends BaseOperation {
} else {
updateVersionAndDate(artifactData, oldVesrion);
}
+ long time = System.currentTimeMillis();
+ artifactData.setHeatParamsUpdateDate(time);
break;
case HEAT:
case HEAT_NET:
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
index 0b60a07a28..1726c397ad 100644
--- 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
@@ -53,8 +53,6 @@ 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.ComponentInstance;
-import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -1189,13 +1187,8 @@ public abstract class BaseOperation {
}
if (result == null) {
toscaDataVertex = toscaDataVertexRes.left().value();
- existingToscaDataMap = (Map<String, ToscaDataDefinition>) getDeepElements(toscaDataVertexRes.left().value(), pathKeys);
- for (String uniqueKey : uniqueKeys) {
- result = removeToscaDataElement(toscaElement, edgeLabel, uniqueKey, toscaDataVertex, existingToscaDataMap);
- if (result != StorageOperationStatus.OK) {
- break;
- }
- }
+ existingToscaDataMap = getDeepElements(toscaDataVertexRes.left().value(), pathKeys);
+ result = deleteElementsFromDataVertex(toscaElement, edgeLabel, uniqueKeys, toscaDataVertex, existingToscaDataMap);
}
if (result == null) {
result = StorageOperationStatus.OK;
@@ -1203,6 +1196,19 @@ public abstract class BaseOperation {
return result;
}
+ private StorageOperationStatus deleteElementsFromDataVertex(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List<String> uniqueKeys, GraphVertex toscaDataVertex, Map<String, ToscaDataDefinition> existingToscaDataMap) {
+ StorageOperationStatus result;
+ for (String uniqueKey : uniqueKeys) {
+ result = removeKeyFromDataVertex(uniqueKey, existingToscaDataMap);
+ if (result != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, 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
*
@@ -1229,7 +1235,6 @@ public abstract class BaseOperation {
* @return
*/
public StorageOperationStatus deleteToscaDataElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List<String> uniqueKeys) {
-
StorageOperationStatus result = null;
GraphVertex toscaDataVertex;
Map<String, ToscaDataDefinition> existingToscaDataMap;
@@ -1242,12 +1247,7 @@ public abstract class BaseOperation {
if (result == null) {
toscaDataVertex = toscaDataVertexRes.left().value();
existingToscaDataMap = (Map<String, ToscaDataDefinition>) toscaDataVertex.getJson();
- for (String uniqueKey : uniqueKeys) {
- result = removeToscaDataElement(toscaElement, edgeLabel, uniqueKey, toscaDataVertex, existingToscaDataMap);
- if (result != StorageOperationStatus.OK) {
- break;
- }
- }
+ result = deleteElementsFromDataVertex(toscaElement, edgeLabel, uniqueKeys, toscaDataVertex, existingToscaDataMap);
}
if (result == null) {
result = StorageOperationStatus.OK;
@@ -1255,23 +1255,24 @@ public abstract class BaseOperation {
return result;
}
- private <T extends ToscaDataDefinition> StorageOperationStatus removeToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, String uniqueKey, GraphVertex toscaDataVertex, Map<String, T> existingToscaDataMap) {
-
+ private <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex) {
StorageOperationStatus result = StorageOperationStatus.OK;
- if (!existingToscaDataMap.containsKey(uniqueKey)) {
- result = StorageOperationStatus.NOT_FOUND;
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete tosca data element of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result);
- } else {
- existingToscaDataMap.remove(uniqueKey);
- Either<GraphVertex, TitanOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel);
- if (updateOrCopyRes.isRight()) {
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(updateOrCopyRes.right().value());
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), result);
- }
+ Either<GraphVertex, TitanOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel);
+ if (updateOrCopyRes.isRight()) {
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(updateOrCopyRes.right().value());
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), result);
}
return result;
}
+ private <T extends ToscaDataDefinition> StorageOperationStatus removeKeyFromDataVertex(String uniqueKey, Map<String, T> existingToscaDataMap) {
+ if (!existingToscaDataMap.containsKey(uniqueKey)) {
+ return StorageOperationStatus.NOT_FOUND;
+ }
+ existingToscaDataMap.remove(uniqueKey);
+ return StorageOperationStatus.OK;
+ }
+
protected <K extends ToscaDataDefinition> StorageOperationStatus handleToscaData(GraphVertex toscaElement, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex, Map<String, K> mergedToscaDataMap) {
StorageOperationStatus result = StorageOperationStatus.OK;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java
index 5f7502e7ce..f7e4245492 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java
@@ -20,13 +20,7 @@
package org.openecomp.sdc.be.model.jsontitan.operations;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-import org.apache.tinkerpop.shaded.minlog.Log;
+import fj.data.Either;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
@@ -34,11 +28,9 @@ import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupInstance;
@@ -48,20 +40,17 @@ import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
-import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.resources.data.GroupData;
-import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.carrotsearch.junitbenchmarks.annotation.LabelType;
-import com.thinkaurelius.titan.diskstorage.Entry;
-
-import fj.data.Either;
-import javassist.expr.NewArray;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("groups-operation")
public class GroupsOperation extends BaseOperation {
@@ -242,7 +231,7 @@ public class GroupsOperation extends BaseOperation {
*/
private String increaseMajorVersion(String version) {
- String[] versionParts = version.split(LifecycleOperation.VERSION_DELIMETER_REGEXP);
+ String[] versionParts = version.split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP);
Integer majorVersion = Integer.parseInt(versionParts[0]);
majorVersion++;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java
index 66d26c748f..b642410548 100644
--- 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
@@ -1620,6 +1620,14 @@ public class NodeTemplateOperation extends BaseOperation {
}
public StorageOperationStatus addDeploymentArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts) {
+ return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS);
+ }
+
+ public StorageOperationStatus addInformationalArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts) {
+ return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS);
+ }
+
+ public StorageOperationStatus addArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexType) {
Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse);
if (metadataVertex.isRight()) {
TitanOperationStatus status = metadataVertex.right().value();
@@ -1629,7 +1637,7 @@ public class NodeTemplateOperation extends BaseOperation {
return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
}
MapArtifactDataDefinition instArtifacts = new MapArtifactDataDefinition(instDeplArtifacts);
- return addToscaDataDeepElementsBlockToToscaElement(metadataVertex.left().value(), EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts, instanceId);
+ return addToscaDataDeepElementsBlockToToscaElement(metadataVertex.left().value(),edgeLabel, vertexType, instArtifacts, instanceId);
}
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
index 2d160bfc82..989707bf0c 100644
--- 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
@@ -349,9 +349,17 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return StorageOperationStatus.OK;
}
- public StorageOperationStatus associateInstArtifactToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instProps) {
+ public StorageOperationStatus associateInstDeploymentArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instArtifacts) {
+ return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ }
+
+ public StorageOperationStatus associateInstArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instArtifacts) {
+ return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ }
+
+ private StorageOperationStatus associateInstanceArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instProps, VertexTypeEnum vertexType, EdgeLabelEnum edgeLabel) {
if (instProps != null && !instProps.isEmpty()) {
- Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, instProps);
+ Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, vertexType, edgeLabel, instProps);
if (assosiateElementToData.isRight()) {
return assosiateElementToData.right().value();
}
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
index d34d3aa9f9..51d122524c 100644
--- 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
@@ -767,6 +767,12 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
}
if (result == null) {
+ Either<GraphVertex, StorageOperationStatus> updateRelationsRes = updateLastModifierEdge(toscaElement, owner, modifier);
+ if (updateRelationsRes.isRight()) {
+ result = updateRelationsRes.right().value();
+ }
+ }
+ if (result == null) {
result = StorageOperationStatus.OK;
}
return result;
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
index 5aceb2ffd2..708ef783f1 100644
--- 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
@@ -1068,7 +1068,7 @@ public abstract class ToscaElementOperation extends BaseOperation {
public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes, boolean isHighestVersions) {
Either<List<GraphVertex>, TitanOperationStatus> listOfComponents;
if (isHighestVersions) {
- listOfComponents = getListOfHighestComponents(componentType, excludeTypes);
+ listOfComponents = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.NoParse);
}
else {
listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes);
@@ -1095,7 +1095,7 @@ public abstract class ToscaElementOperation extends BaseOperation {
return Either.left(result);
}
- private Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes) {
+ private Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes, JsonParseFlagEnum parseFlag) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>();
Map<GraphPropertyEnum, Object> propertiesHasNotToMatch = new HashMap<>();
propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
@@ -1107,13 +1107,13 @@ public abstract class ToscaElementOperation extends BaseOperation {
}
propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
- return titanDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
+ return titanDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag);
}
// highest + (certified && !highest)
public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes) {
long startFetchAllStates = System.currentTimeMillis();
- Either<List<GraphVertex>, TitanOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes);
+ Either<List<GraphVertex>, TitanOperationStatus> highestNodes = getListOfHighestComponents(componentType, excludeTypes, JsonParseFlagEnum.ParseMetadata);
Map<GraphPropertyEnum, Object> propertiesToMatchCertified = new HashMap<>();
Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new HashMap<>();
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
index 45a1f2bd31..e3ed9d6471 100644
--- 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
@@ -25,6 +25,7 @@ import fj.data.Either;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
@@ -1097,7 +1098,34 @@ public class ToscaOperationFacade {
}
- public StorageOperationStatus associateArtifactToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) {
+ public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, String componentId, User user) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value());
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
+ if (instDeploymentArtifacts != null) {
+
+ MapArtifactDataDefinition artifactsMap;
+ for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) {
+ Map<String, ArtifactDefinition> artList = entry.getValue();
+ Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+ artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
+
+ instArtMap.put(entry.getKey(), artifactsMap);
+ }
+ }
+
+ return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap);
+
+ }
+
+ public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) {
Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
@@ -1114,13 +1142,13 @@ public class ToscaOperationFacade {
for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) {
Map<String, ArtifactDefinition> artList = entry.getValue();
Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
- artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME);
+ artifactsMap = new MapArtifactDataDefinition(artifacts);
instArtMap.put(entry.getKey(), artifactsMap);
}
}
- return topologyTemplateOperation.associateInstArtifactToComponent(vertex, instArtMap);
+ return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap);
}
@@ -1913,6 +1941,15 @@ public class ToscaOperationFacade {
return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
}
+
+ public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) {
+ StorageOperationStatus status = StorageOperationStatus.OK;
+ if(MapUtils.isNotEmpty(artifacts)){
+ Map<String, ArtifactDataDefinition> 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);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java
index 5e8a2eb0d5..3d689a4f93 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java
@@ -39,42 +39,10 @@ public interface IArtifactOperation {
public Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, boolean inTransaction);
- public Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinition(ArtifactDefinition artifactInfo, boolean inTransaction);
-
public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum resource, boolean deleteMandatoryArtifact, boolean inTransaction);
public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction);
- public void setTitanGenericDao(TitanGenericDao titanGenericDao);
-
- public Either<ArtifactDefinition, StorageOperationStatus> getArtifactById(String id, boolean inTransaction);
-
- public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, String groupType);
-
- Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String parentId, NodeTypeEnum parentType, boolean failIfExist);
-
- public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion);
-
- public Either<Integer, StorageOperationStatus> getParentsOfArtifact(String artifactId, NodeTypeEnum type);
-
- public Either<ArtifactDefinition, StorageOperationStatus> getHeatArtifactByHeatEnvId(String heatEnvId, boolean inTransaction);
-
- public Either<ArtifactData, StorageOperationStatus> updateToscaArtifactNameOnGraph(ArtifactDefinition artifactInfo, String artifactId, NodeTypeEnum type, String id);
-
-
public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, TitanVertex parentVertex);
- public Either<ArtifactData, StorageOperationStatus> getLatestArtifactDataByArtifactUUID(String artifactUUID, boolean inTransaction);
-
- StorageOperationStatus addArifactToComponent(TitanVertex artifactInfo, TitanVertex parentVertex, String label);
-
- public Either<ArtifactData, TitanOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact);
-
- public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, boolean inTransaction);
-
- public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact( String id, ArtifactDefinition artifactEnvInfo, String oldArtifactId, String newArtifactId, NodeTypeEnum type, boolean inTransaction);
-
- public Either<ArtifactDefinition, StorageOperationStatus> getHeatEnvByGeneratedFromId(String generatedFromId);
-
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAttributeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAttributeOperation.java
deleted file mode 100644
index c5fc70eb38..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAttributeOperation.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.api;
-
-import java.util.List;
-import java.util.Map;
-
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.resources.data.AttributeData;
-import org.openecomp.sdc.be.resources.data.AttributeValueData;
-
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-public interface IAttributeOperation {
- Either<AttributeData, StorageOperationStatus> deleteAttribute(String attributeId);
-
- TitanOperationStatus addAttributesToGraph(TitanVertex metadataVertex, Map<String, PropertyDefinition> attributes, String resourceId, Map<String, DataTypeDefinition> dataTypes);
-
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> getAllAttributesOfResourceInstance(ComponentInstance compInstance);
-
- TitanOperationStatus findAllResourceAttributesRecursively(String resourceId, List<PropertyDefinition> attributes);
-
- Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllAttributeAssociatedToNode(NodeTypeEnum nodeType, String uniqueId);
-
- TitanOperationStatus findNodeNonInheretedAttribues(String uniqueId, NodeTypeEnum nodeType, List<PropertyDefinition> attributes);
-
- Either<AttributeData, StorageOperationStatus> addAttribute(PropertyDefinition attributeDefinition, String resourceId);
-
- Either<AttributeData, TitanOperationStatus> addAttributeToGraph(PropertyDefinition attribute, String resourceId, Map<String, DataTypeDefinition> dataTypes);
-
- PropertyDefinition convertAttributeDataToAttributeDefinition(AttributeData attributeData, String attributeName, String resourceId);
-
- Either<AttributeData, StorageOperationStatus> updateAttribute(String attributeId, PropertyDefinition newAttDef, Map<String, DataTypeDefinition> dataTypes);
-
- /**
- * Builds ComponentInstanceAttribute from AttributeValueData
- *
- * @param attributeValueData
- * @param resourceInstanceAttribute
- * @return
- */
- ComponentInstanceProperty buildResourceInstanceAttribute(AttributeValueData attributeValueData, ComponentInstanceProperty resourceInstanceAttribute);
-
- TitanOperationStatus addAttributeToGraphByVertex(TitanVertex metadataVertex, PropertyDefinition attribute, String resourceId, Map<String, DataTypeDefinition> dataTypes);
-
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java
deleted file mode 100644
index f8e8c80f12..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.api;
-
-import java.util.List;
-import java.util.Map;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.resources.data.CapabilityInstData;
-import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
-import org.openecomp.sdc.be.resources.data.PropertyValueData;
-
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-/**
- * public interface ICapabilityInstanceOperation provides methods for CRUD operations for CapabilityInstance on component instance level
- *
- * @author ns019t
- *
- */
-public interface ICapabilityInstanceOperation {
- /**
- * create capability instance of capability with property values for resource instance
- *
- * @param resourceInstanceId
- * @param capabilityId
- * @param propertyValues
- * @param validateCapabilityInstExistance
- * @param capabilityName
- * @return
- */
- public Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(String resourceInstanceId, String capabilityId, String capabilityName,
- List<ComponentInstanceProperty> propertyValues, boolean validateCapabilityInstExistance);
-
- /**
- *
- * @param resourceInstanceVertex
- * @param capabilityId
- * @param capabilityName
- * @param propertyValues
- * @param validateCapabilityInstExistence
- * @return
- */
- public TitanOperationStatus createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(TitanVertex resourceInstanceVertex, String resourceInstanceId, String capabilityId, String capabilityName,
- List<ComponentInstanceProperty> propertyValues, boolean validateCapabilityInstExistence);
-
- /**
- * validate capability instance uniqueness
- *
- * @param resourceInstanceId
- * @param capabilityId
- * @return
- */
- public Either<Boolean, TitanOperationStatus> validateCapabilityInstExistence(String resourceInstanceId, String capabilityId);
-
- /**
- * delete capability instance from resource instance
- *
- * @param resourceInstanceId
- * @param capabilityInstanceId
- * @return
- */
- public Either<CapabilityInstData, TitanOperationStatus> deleteCapabilityInstanceFromResourceInstance(String resourceInstanceId, String capabilityInstanceId);
-
- /**
- * get all capability instances for resource instance returns all Capability Instances related to Resource Instance as List<CapabilityInstData> or TitanOperationStatus if error occurs or if Resource Instance have no any related Capability
- * Instance
- *
- * @param resourceInstanceId
- * @return Either<List<CapabilityInstData>, TitanOperationStatus>
- */
- public Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesOfResourceInstance(String resourceInstanceId);
-
- /**
- * get capability instance of capability for resource instance
- *
- * @param resourceInstanceId
- * @param capabilityId
- * @return
- */
- public Either<CapabilityInstData, TitanOperationStatus> getCapabilityInstanceOfCapabilityOfResourceInstance(String resourceInstanceId, String capabilityId);
-
- /**
- * update capability property values
- *
- * @param resourceInstanceId
- * @param capabilityInstanceId
- * @param propertyValues
- * @param capabilityId
- * @return
- */
- public Either<List<PropertyValueData>, TitanOperationStatus> updateCapabilityPropertyValues(String resourceInstanceId, String capabilityId, List<ComponentInstanceProperty> propertyValues);
-
- /**
- * clone and associate capability instance with property values
- *
- * @param createdComponentInstance
- * @param capability
- * @param capabilityInstPair
- * @return
- */
- public Either<ImmutablePair<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> cloneAssociateCapabilityInstanceWithPropertyValues(ComponentInstanceData createdComponentInstance, CapabilityDefinition capability,
- ImmutablePair<CapabilityInstData, GraphEdge> capabilityInstPair);
-
- Either<Boolean, TitanOperationStatus> validateCapabilityInstExistence(TitanVertex instanceVertex, String resourceInstanceId, String capabilityId);
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java
index b3be2bd6ee..b90f31f731 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java
@@ -38,36 +38,8 @@ import fj.data.Either;
public interface ICapabilityOperation {
- public Either<CapabilityDefinition, StorageOperationStatus> addCapability(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition);
+ Either<Map<String, PropertyDefinition>, TitanOperationStatus> getAllCapabilityTypePropertiesFromAllDerivedFrom(String firstParentType);
- public Either<CapabilityDefinition, StorageOperationStatus> addCapability(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition, boolean inTransaction);
-
- /**
- * @param uniqueId
- * @return
- */
- public Either<CapabilityDefinition, StorageOperationStatus> getCapability(String uniqueId);
-
- public Either<CapabilityDefinition, StorageOperationStatus> getCapability(String uniqueId, boolean inTransaction);
-
- public Either<CapabilityDefinition, StorageOperationStatus> getCapability(String capabilityName, String resourceId);
-
- public Either<CapabilityDefinition, StorageOperationStatus> getCapability(String capabilityName, String resourceId, boolean inTransaction);
-
- public Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getAllCapabilitiesPairs(String resourceId);
-
- public Either<Map<String, CapabilityDefinition>, StorageOperationStatus> deleteAllCapabilities(String resourceId, boolean inTransaction);
-
- public Either<CapabilityDefinition, TitanOperationStatus> getCapabilityByCapabilityData(CapabilityData capabilityData);
-
- public TitanOperationStatus getCapabilitySourcesList(String resourceId, List<String> derivedFromList);
-
- public Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId, String capabilityType, List<PropertyDefinition> newProperties);
-
- public Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId, String capabilityType, List<PropertyDefinition> newProperties, boolean inTransaction);
-
- StorageOperationStatus addCapability(TitanVertex metadataVertex, String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition, boolean inTransaction);
-
- Either<CapabilityTypeData, TitanOperationStatus> getCapabilityTypeOfCapability(String uniqueId);
+ Either<List<PropertyDefinition>, TitanOperationStatus> validatePropertyUniqueness(Map<String, PropertyDefinition> propertiesOfCapabilityType, List<PropertyDefinition> properties);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java
index f4cb13fa64..d1a1b6ac7b 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java
@@ -45,149 +45,8 @@ import fj.data.Either;
public interface IComponentInstanceOperation {
- /**
- * add resource instance to service
- *
- * @param containerComponentId
- * - component id
- * @param instanceNumber
- * - instance number of the component instance
- * @param componentInstance
- * @param inTransaction
- * @return
- */
- public Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance, NodeTypeEnum instNodeType,
- boolean inTransaction);
-
- /**
- * add resource instance to service with internal transaction
- *
- * @param containerComponentId
- * @param instanceNumber
- * @param componentInstance
- * @return
- */
- public Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance, NodeTypeEnum instNodeType);
-
- /**
- * delete resource instance from component
- *
- * @param containerComponentId
- * - containerComponent id
- * @param resourceInstUid
- * - resource instance uid
- * @param inTransaction
- * @return
- */
- public Either<ComponentInstance, StorageOperationStatus> deleteComponentInstance(NodeTypeEnum containerNodeType, String containerComponentId, String resourceInstUid, boolean inTransaction);
-
- public Either<ComponentInstance, StorageOperationStatus> deleteComponentInstance(NodeTypeEnum containerNodeType, String containerComponentId, String resourceInstUid);
-
- /**
- * associate 2 resource instances for a given requirement
- *
- * @param serviceId
- * @param fromResInstanceUid
- * @param toResInstanceUid
- * @param requirement
- * @param relationship
- * @param inTransaction
- * @return
- */
- // public Either<RequirementCapabilityRelDef, StorageOperationStatus>
- // associateResourceInstances(
- // String serviceId, NodeTypeEnum nodeType, String fromResInstanceUid,
- // String toResInstanceUid, String requirement, String relationship,
- // boolean inTransaction);
-
- // public Either<RequirementCapabilityRelDef, StorageOperationStatus>
- // associateResourceInstances(
- // String serviceId, NodeTypeEnum nodeType, String fromResInstanceUid,
- // String toResInstanceUid, String requirement, String relationship);
-
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean inTransaction, boolean isClone);
-
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation);
-
- /**
- *
- * dissociate the relation between 2 resource instances for a given requirement
- *
- * @param serviceId
- * @param fromResInstanceUid
- * @param toResInstanceUid
- * @param requirement
- * @param inTransaction
- * @return
- */
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef, boolean inTransaction);
-
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef);
-
- /**
- * update the properties of a given resource instance
- *
- * @param serviceId
- * @param resourceInstanceName
- * @param resourceInstance
- * @param inTransaction
- * @return
- */
- public Either<ComponentInstance, StorageOperationStatus> updateResourceInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance, boolean inTransaction);
-
- public Either<ComponentInstance, StorageOperationStatus> updateResourceInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance);
-
- /**
- * get all resource instances of a given service and the relations between the resource instances
- *
- * @param serviceId
- * @param inTransaction
- * @return
- */
- public Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> getAllComponentInstances(String componentId, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, boolean inTransaction);
-
- public Either<List<String>, StorageOperationStatus> getAllComponentInstancesNames(String componentId, NodeTypeEnum nodeType, boolean inTransaction);
-
- public Either<List<String>, StorageOperationStatus> getAllComponentInstancesNames(String componentId, NodeTypeEnum nodeType);
-
- /**
- * get all component instance properties and values from graph
- * @param resourceInstance
- * @return
- */
- public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstancesPropertiesAndValuesFromGraph(
- ComponentInstance resourceInstance);
-
- /**
- * get resource instance from id
- *
- * @param resourceId
- * @return resource instance of given id
- */
- public Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(String resourceId);
-
- public Either<List<ComponentInstance>, StorageOperationStatus> deleteAllComponentInstances(String serviceId, NodeTypeEnum nodeType, boolean inTransaction);
-
- public Either<List<ComponentInstance>, StorageOperationStatus> deleteAllComponentInstances(String serviceId, NodeTypeEnum nodeType);
-
public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction);
- public String createComponentInstLogicalName(String instanceNumber, String componentInstanceName);
-
- public Either<Boolean, StorageOperationStatus> isComponentInstanceNameExist(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName);
-
- public Either<Boolean, StorageOperationStatus> validateParent(String parentId, String uniqId, boolean inTransaction);
-
- public Either<ComponentInstance, StorageOperationStatus> getFullComponentInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType);
-
- public Either<Boolean, StorageOperationStatus> isAvailableRequirement(ComponentInstance fromResInstance, RequirementAndRelationshipPair relationPair);
-
- public Either<Boolean, StorageOperationStatus> isAvailableCapabilty(ComponentInstance toResInstance, RequirementAndRelationshipPair relationPair);
-
- public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, boolean inTransaction);
-
- public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isvalidate, Integer index, boolean inTransaction);
-
/**
* Adds Attribute to resource instance
*
@@ -197,8 +56,6 @@ public interface IComponentInstanceOperation {
**/
public Either<ComponentInstanceProperty, StorageOperationStatus> addAttributeValueToResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction);
- public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean inTransaction);
-
/**
* Updates Attribute on resource instance
*
@@ -209,13 +66,11 @@ public interface IComponentInstanceOperation {
*/
public Either<ComponentInstanceProperty, StorageOperationStatus> updateAttributeValueInResourceInstance(ComponentInstanceProperty attribute, String resourceInstanceId, boolean inTransaction);
- public Either<AttributeValueData, TitanOperationStatus> createOrUpdateAttributeOfResourceInstance(ComponentInstanceProperty attributeInstanceProperty, String resourceInstanceId);
public Either<ComponentInstanceInput, StorageOperationStatus> addInputValueToResourceInstance(ComponentInstanceInput input, String resourceInstanceId, Integer innerElement, boolean b);
public Either<ComponentInstanceInput, StorageOperationStatus> updateInputValueInResourceInstance(ComponentInstanceInput input, String resourceInstanceId, boolean b);
- public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId);
public StorageOperationStatus updateCustomizationUUID(String componentInstanceId);
/**
@@ -228,11 +83,4 @@ public interface IComponentInstanceOperation {
*/
public Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction);
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum);
-
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum);
-
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getFulfilledCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum);
-
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getFulfilledRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java
deleted file mode 100644
index 3eef59fa69..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.api;
-
-import java.util.List;
-import java.util.Map;
-
-import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-
-import fj.data.Either;
-
-public interface IComponentOperation {
- public <T extends Component> Either<T, StorageOperationStatus> getComponent(String id, Class<T> clazz);
-
- public Either<List<ArtifactDefinition>, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType, boolean inTransacton);
-
- public <T> Either<T, StorageOperationStatus> getLightComponent(String id, boolean inTransaction);
-
- public <T> Either<T, StorageOperationStatus> getComponent(String id, boolean inTransaction);
-
- public <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTransaction);
-
- public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTranscation);
-
- public <T extends GraphNode> Either<T, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, NodeTypeEnum nodeType, Class<T> clazz);
-
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java
index 8fd88f704f..b55eff6684 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java
@@ -45,57 +45,15 @@ import fj.data.Either;
public interface IGroupInstanceOperation {
- public Either<GroupInstance, StorageOperationStatus> createGroupInstance(String ComponentInstId, GroupInstance groupInstance, boolean isCreateLogicalName);
-
- public Either<GroupInstance, StorageOperationStatus> createGroupInstance(TitanVertex ciVertex, String componentInstId, GroupInstance groupInstance, boolean isCreateLogicalName);
-
- public Either<GroupInstance, StorageOperationStatus> deleteGroupInstanceInstance(NodeTypeEnum containerNodeType, String containerComponentId, String groupInstUid);
-
- public Either<GroupInstance, StorageOperationStatus> updateGroupInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance);
-
- public Either<List<GroupInstance>, StorageOperationStatus> getAllGroupInstances(String componentInstId, NodeTypeEnum compInstNodeType);
-
- public Either<GroupInstance, TitanOperationStatus> getGroupInstanceById(String groupResourceId);
- public TitanOperationStatus deleteAllGroupInstances(String componentInstId);
+ public Either<List<GroupInstance>, StorageOperationStatus> getAllGroupInstances(String componentInstId, NodeTypeEnum compInstNodeType);
public Either<Integer, StorageOperationStatus> increaseAndGetGroupInstancePropertyCounter(String groupInstanceId);
- public Either<Boolean, StorageOperationStatus> isGroupInstanceNameExist(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName);
-
- public Either<ComponentInstance, StorageOperationStatus> getFullGroupInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType);
-
public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, boolean inTransaction);
- public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isvalidate, Integer index, boolean inTransaction);
-
public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInGroupInstance(ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction);
-
- public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId);
-
- public StorageOperationStatus updateCustomizationUUID(String componentInstanceId);
-
- public String createGroupInstLogicalName(String instanceNumber, String groupInstanceName);
-
- public Either<GroupInstance, StorageOperationStatus> associateArtifactsToGroupInstance(String groupId, List<String> artifactsId);
StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact);
- StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact);
- /**
- * updates group instance property values
- * @param value
- * @param newProperties
- * @return
- */
- public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValues(GroupInstance value, List<GroupInstanceProperty> newProperties);
- /**
- * updates group instance property values
- * @param oldGroupInstance
- * @param newProperties
- * @param inTransaction
- * @return
- */
- public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValues(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties, Boolean inTransaction);
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java
index 3295adfe56..6dbbfb6b6e 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java
@@ -34,72 +34,11 @@ import fj.data.Either;
public interface IGroupOperation {
- // add full group to component
- public Either<GroupData, TitanOperationStatus> addGroupToGraph(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition);
-
- public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition);
-
- public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition, boolean inTransaction);
-
- public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(NodeTypeEnum nodeTypeEnum, String componentId, List<GroupDefinition> groups, boolean inTransaction);
-
- // get group
- public Either<GroupDefinition, TitanOperationStatus> getGroupFromGraph(String uniqueId);
-
- public Either<GroupDefinition, StorageOperationStatus> getGroup(String uniqueId);
-
- public Either<GroupDefinition, StorageOperationStatus> getGroup(String uniqueId, boolean inTransaction);
-
- // get all groups under component
- public Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum);
-
- public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction);
-
- public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum);
-
- // delete all groups under component
- public Either<List<GroupDefinition>, TitanOperationStatus> deleteAllGroupsFromGraph(String componentId, NodeTypeEnum compTypeEnum);
-
- public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction);
-
- public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum);
-
- // Association
- public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId, boolean inTransaction);
-
- public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId);
-
- public Either<List<String>, TitanOperationStatus> getAssociatedGroupsToComponentInstanceFromGraph(String componentInstanceId);
-
- public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, String compInstName, boolean inTransaction);
-
- public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, String compInstName);
-
- public Either<List<GraphRelation>, TitanOperationStatus> associateGroupsToComponentInstanceOnGraph(List<String> groups, String componentInstanceId, String compInstName);
-
public Either<List<GraphRelation>, TitanOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String artifactId);
- public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId, boolean inTransaction);
-
- public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId);
-
- public TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact);
-
public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction);
- public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact);
-
public boolean isGroupExist(String groupName, boolean inTransaction);
- /**
- * Updates Group Metadata (name and properties)
- * @param groupToUpdateFromUniqueId
- * @param newName
- * @param groupToUpdateTo
- * @param inTransaction
- * @return
- */
- public Either<GroupDefinition, StorageOperationStatus> updateGroupName(String groupToUpdateFromUniqueId,
- String newName, GroupDefinition groupToUpdateTo, boolean inTransaction);
public StorageOperationStatus validateAndUpdatePropertyValue(GroupProperty property);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java
index 8b44229df1..1cec537e3e 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java
@@ -20,50 +20,21 @@
package org.openecomp.sdc.be.model.operations.api;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.ComponentInstInputsMap;
-import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.resources.data.AttributeData;
+import org.openecomp.sdc.be.resources.data.InputValueData;
import org.openecomp.sdc.be.resources.data.InputsData;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
+import java.util.List;
public interface IInputsOperation {
- Either<InputDefinition, StorageOperationStatus> deleteInput(String inputId);
-
- Either<List<InputDefinition>, TitanOperationStatus> addInputsToGraph(String componentId, NodeTypeEnum nodeType, Map<String, InputDefinition> inputs, Map<String, DataTypeDefinition> dataTypes);
-
- TitanOperationStatus findNodeNonInheretedInputs(String uniqueId, List<InputDefinition> inputs);
-
- Either<List<InputDefinition>, StorageOperationStatus> getInputsOfComponent(String compId, String fromName, int amount);
-
- Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllInputsOfResourceInstance(ComponentInstance compInstance);
-
- Either<Map<String, InputDefinition>, StorageOperationStatus> deleteAllInputsAssociatedToNode(NodeTypeEnum nodeType, String uniqueId);
-
- // TitanOperationStatus findNodeNonInheretedAttribues(String uniqueId,
- // NodeTypeEnum nodeType, List<AttributeDefinition> attributes);
-
- Either<InputsData, StorageOperationStatus> addInput(String inputName, InputDefinition inputDefinition, String componentId, NodeTypeEnum nodeType);
-
- Either<InputsData, TitanOperationStatus> addInputToGraph(String propertyName, InputDefinition inputDefinition, String componentId, NodeTypeEnum nodeType);
-
- Either<AttributeData, StorageOperationStatus> updateInput(String inputId, InputDefinition newInDef, Map<String, DataTypeDefinition> dataTypes);
-
- TitanOperationStatus findAllResourceInputs(String uniqueId, List<InputDefinition> inputs);
-
- Either<InputDefinition, StorageOperationStatus> getInputById(String uniqueId, boolean skipProperties, boolean skipinputsValue);
+ ImmutablePair<TitanOperationStatus, String> findInputValue(String resourceInstanceId, String propertyId);
- TitanOperationStatus addInputsToGraph(TitanVertex metadata, String componentId, Map<String, InputDefinition> inputs, Map<String, DataTypeDefinition> dataTypes);
+ ComponentInstanceInput buildResourceInstanceInput(InputValueData propertyValueData, ComponentInstanceInput resourceInstanceInput);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java
index e46460a502..c9a332f069 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java
@@ -35,43 +35,23 @@ public interface IInterfaceLifecycleOperation {
public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction);
- public StorageOperationStatus createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction, TitanVertex metadataVertex);
-
- public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName);
-
public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean inTransaction);
- // public Either<InterfaceDefinition, StorageOperationStatus>
- // getInterface(String interfaceId);
- //
- // public Either<InterfaceDefinition, StorageOperationStatus>
- // getInterface(String interfaceId, boolean inTransaction);
-
public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf);
public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf, boolean inTransaction);
- public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationName);
-
public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationName, boolean inTransaction);
public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively, boolean inTransaction);
public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively);
- public Either<InterfaceDefinition, StorageOperationStatus> deleteInterfaceOfResourceOnGraph(String resourceId, InterfaceDefinition interfaceDef, boolean inTransaction);
-
public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf);
public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf, boolean inTransaction);
public Either<InterfaceDefinition, StorageOperationStatus> getInterface(String interfaceId);
- public StorageOperationStatus associateInterfaceToNode(GraphNode node, InterfaceDefinition interfaceDefinition, TitanVertex metadataVertex);
-
- public Either<Operation, StorageOperationStatus> getSpecificOperation(String resourceId, String interfaceType, String operationName);
-
- public Either<InterfaceDefinition, StorageOperationStatus> dissociateInterfaceFromNode(GraphNode node, InterfaceDefinition interfaceDefinition);
-
public String getShortInterfaceName(InterfaceDataDefinition interfaceDefinition);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java
deleted file mode 100644
index ab99f20d4c..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.api;
-
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-
-import fj.data.Either;
-
-public interface ILifecycleOperation {
-
- public ResourceOperation getResourceOperation();
-
- public Either<User, StorageOperationStatus> getComponentOwner(String resourceId, NodeTypeEnum nodeType, boolean inTransaction);
-
- public Either<? extends Component, StorageOperationStatus> checkinComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction);
-
- public Either<? extends Component, StorageOperationStatus> requestCertificationComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction);
-
- public Either<? extends Component, StorageOperationStatus> startComponentCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction);
-
- public Either<? extends Component, StorageOperationStatus> checkoutComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction);
-
- public Either<? extends Component, StorageOperationStatus> certifyComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction);
-
- public Either<? extends Component, StorageOperationStatus> cancelOrFailCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, LifecycleStateEnum nextState, boolean b);
-
- public Either<Boolean, StorageOperationStatus> deleteOldComponentVersions(NodeTypeEnum nodeType, String componentName, String uuid, boolean inTransaction);
-
- public Either<? extends Component, StorageOperationStatus> undoCheckout(NodeTypeEnum nodeType, Component resource, User modifier, User currentOwner, boolean inTransaction);
-
- public ComponentOperation getComponentOperation(NodeTypeEnum componentType);
-
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java
deleted file mode 100644
index 76f95f3c2b..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.api;
-
-import java.util.List;
-import java.util.Set;
-
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Product;
-
-import fj.data.Either;
-
-public interface IProductOperation extends IComponentOperation {
- public Either<List<Product>, StorageOperationStatus> getProductCatalogData(boolean inTransaction);
-
- public Either<Product, StorageOperationStatus> createProduct(Product product);
-
- public Either<Product, StorageOperationStatus> createProduct(Product product, boolean inTransaction);
-
- public Either<Product, StorageOperationStatus> deleteProduct(String productId, boolean inTransaction);
-
- public Either<List<Product>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction);
-
- public void rollback();
-
- public void commit();
-
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java
index f9f960fdbf..3dd49f1aee 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java
@@ -33,29 +33,6 @@ import fj.data.Either;
public interface IPropertyOperation {
/**
- * add property to resource
- *
- * @param propertyName
- * @param propertyDefinition
- * @param nodeType
- * @param id
- * @return
- *
- * public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource( String propertyName, PropertyDefinition propertyDefinition, NodeTypeEnum nodeType, String id);
- */
-
- /**
- * get property belongs to resource
- *
- * @param propertyName
- * - property name
- * @param resourceId
- * - resource unique id
- * @return
- */
- public Either<PropertyDefinition, StorageOperationStatus> getPropertyOfResource(String propertyName, String resourceId);
-
- /**
* Delete all properties of resource
*
* @param nodeType
@@ -76,8 +53,6 @@ public interface IPropertyOperation {
*/
public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition);
- public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition, boolean inTransaction);
-
/**
* @param name
* @return
@@ -86,14 +61,10 @@ public interface IPropertyOperation {
public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByName(String name, boolean inTransaction);
- public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameWithoutDerived(String name, boolean inTransaction);
-
public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameWithoutDerived(String name);
public StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes);
- public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition, boolean inTransaction);
-
public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java
deleted file mode 100644
index a2af44cf61..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.api;
-
-import java.util.List;
-import java.util.Map;
-
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.RequirementImplDef;
-
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-public interface IRequirementOperation {
-
- /**
- * add a requirement to resource
- *
- * @param reqName
- * @param reqDefinition
- * @param nodeType
- * @param uniqueId
- * @return
- */
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId);
-
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction);
-
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId);
-
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId, boolean inTransaction);
-
- /**
- * get requirement of resource
- *
- * @param reqName
- * @param resourceId
- * @return
- */
- public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, String resourceId);
-
- public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, String resourceId, boolean inTransaction);
-
- public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements(String resourceId, boolean inTransaction);
-
- Either<Map<String, List<RequirementDefinition>>, StorageOperationStatus> getAllRequirementsOfResourceOnly(String resourceId, boolean inTransaction);
-
- public Either<Map<String, RequirementDefinition>, TitanOperationStatus> getResourceRequirements(String resourceId);
-
- public Either<Map<String, RequirementDefinition>, StorageOperationStatus> deleteAllRequirements(String resourceId, boolean inTransaction);
-
- public Either<RequirementDefinition, TitanOperationStatus> getRequirement(String uniqueId);
-
- StorageOperationStatus addRequirementToResource(TitanVertex metadataVertex, String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction);
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java
deleted file mode 100644
index 8d9994ba8a..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.api;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Resource;
-
-import fj.data.Either;
-
-public interface IResourceOperation extends IComponentOperation {
-
- public TitanGenericDao getTitanGenericDao();
-
- // public StorageOperationStatus lockResource(Resource resource);
- //
- // public StorageOperationStatus unlockResource(Resource resource);
-
- public Either<Resource, StorageOperationStatus> createResource(Resource resource);
-
- public Either<Resource, StorageOperationStatus> createResource(Resource resource, boolean inTransaction);
-
- public Either<Resource, StorageOperationStatus> getResource(String resourceId);
-
- // public Either<Resource, StorageOperationStatus> getResource_tx(String
- // resourceId,boolean inTransaction);
-
- public Either<Resource, StorageOperationStatus> getResource(String resourceId, boolean inTransaction);
-
- /**
- * the method retrieves all the certified resources, the returned values are only abstract or only none abstract according to the supplied parameters.
- *
- * @param getAbstract
- * the value defines which resources to return only abstract or only none abstract
- * @return
- */
- public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean getAbstract);
-
- public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean getAbstract, Boolean isHighest);
-
- public Either<Boolean, StorageOperationStatus> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceType);
-
- public Either<Resource, StorageOperationStatus> deleteResource(String resourceId);
-
- public Either<Resource, StorageOperationStatus> deleteResource(String resourceId, boolean inTransaction);
-
- public Either<Resource, StorageOperationStatus> updateResource(Resource resource);
-
- public Either<Resource, StorageOperationStatus> updateResource(Resource resource, boolean inTransaction);
-
- public Either<Integer, StorageOperationStatus> getNumberOfResourcesByName(String resourceName);
-
- // public Either<List<ArtifactDefinition>, StorageOperationStatus>
- // getResourceArtifactsForDelete(Resource resource);
-
- public Either<List<Resource>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction);
-
- public Either<Set<Resource>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch, boolean inTransaction);
-
- public Either<Resource, StorageOperationStatus> getLatestByName(String resourceName, boolean inTransaction);
-
- public Either<Resource, StorageOperationStatus> overrideResource(Resource resource, Resource resourceSaved, boolean inTransaction);
-
- public Either<List<Resource>, StorageOperationStatus> getTesterFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction);
-
- public Either<List<Resource>, StorageOperationStatus> getResourceListByUuid(String uuid, boolean inTransaction);
-
- public Either<List<Resource>, StorageOperationStatus> getLatestResourceByUuid(String uuid, boolean inTransaction);
-
- public Either<List<Resource>, StorageOperationStatus> getResourceListBySystemName(String systemName, boolean inTransaction);
-
- public Either<List<Resource>, StorageOperationStatus> getResourceCatalogData(boolean inTransaction);
-
- public Either<List<Resource>, StorageOperationStatus> getResourceCatalogDataVFLatestCertifiedAndNonCertified(boolean inTransaction);
-
- public Either<List<Resource>, StorageOperationStatus> getResourceByNameAndVersion(String name, String version, boolean inTransaction);
-
- public Either<List<Resource>, StorageOperationStatus> getResourceByNameAndVersion(String name, String version);
-
- public Either<Resource, StorageOperationStatus> getResourceBySystemNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction);
-
- // public Either<List<Resource>, StorageOperationStatus>
- // getAllNotCheckoutResources(boolean getAbstract);
-
- // public Either<List<Resource>, StorageOperationStatus>
- // getAllNotCheckoutResources(boolean getAbstract, Boolean isHighest);
-
- public Either<List<String>, StorageOperationStatus> getAllResourcesMarkedForDeletion();
-
- public Either<Boolean, StorageOperationStatus> isResourceInUse(String resourceToDelete);
-
- public Either<Resource, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName, boolean inTransaction);
-
- public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName);
-
- public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends);
-
- /**
- *
- * @param resource the resource to look for its derived resources
- * @return all resources which derives from the given resource
- */
- Either<List<Resource>, StorageOperationStatus> getAllDerivedResources(Resource resource);
-
- /**
- *
- * @return all root resources (i.e all normatives with tosca name {@code Resource.ROOT_RESOURCE}
- */
- Either<List<Resource>, StorageOperationStatus> getRootResources();
-
- /**
- *
- * @return all resources with type VF
- */
- Either<List<Resource>, StorageOperationStatus> getVFResources();
-
-
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java
deleted file mode 100644
index 51f21ce5b8..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.api;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.openecomp.sdc.be.model.*;
-
-import fj.data.Either;
-
-public interface IServiceOperation extends IComponentOperation {
-
- public Either<Service, StorageOperationStatus> createService(Service service);
-
- public Either<Service, StorageOperationStatus> createService(Service service, boolean inTransaction);
-
- public Either<Service, StorageOperationStatus> getService(String uniqueId);
-
- public Either<Service, StorageOperationStatus> getService(String uniqueId, boolean inTransaction);
-
- public Either<Service, StorageOperationStatus> getService(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction);
-
- public Either<Service, StorageOperationStatus> deleteService(String uniqueId);
-
- public Either<Service, StorageOperationStatus> deleteService(String uniqueId, boolean inTransaction);
-
- public Either<Boolean, StorageOperationStatus> validateServiceNameExists(String serviceName);
-
- public Either<List<Service>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction);
-
- public Either<Service, StorageOperationStatus> updateService(Service service, boolean inTransaction);
-
- public Either<Set<Service>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch, boolean inTransaction);
-
- public Either<List<Service>, StorageOperationStatus> getTesterFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction);
-
- public Either<Set<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Map<String, Object> propertiesToMatch, Set<DistributionStatusEnum> distStatus, boolean inTransaction);
-
- public Either<Service, StorageOperationStatus> updateDestributionStatus(Service service, User user, DistributionStatusEnum distributionStatus);
-
- public Either<List<Service>, StorageOperationStatus> getServiceCatalogData(boolean inTransaction);
-
- public Either<List<Service>, StorageOperationStatus> getServiceCatalogDataLatestCertifiedAndNotCertified(boolean inTransaction);
-
- public Either<Service, StorageOperationStatus> getServiceByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction);
-
- public Either<Service, StorageOperationStatus> getServiceByNameAndVersion(String name, String version);
-
- public Either<Service, StorageOperationStatus> getServiceBySystemNameAndVersion(String name, String version, boolean inTransaction);
-
- public Either<List<Service>, StorageOperationStatus> getServiceListByUuid(String uuid, boolean inTransaction);
-
- public Either<List<Service>, StorageOperationStatus> getLatestServiceByUuid(String uuid, boolean inTransaction);
-
- public Either<List<Service>, StorageOperationStatus> getServiceListBySystemName(String systemName, boolean inTransaction);
-
- Either<List<Service> , StorageOperationStatus> getAll();
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java
index 254432c682..3df954fc36 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java
@@ -36,8 +36,6 @@ public interface IUserAdminOperation {
public Either<User, ActionStatus> getUserData(String id, boolean inTransaction);
- public Either<User, ActionStatus> getInactiveUserData(String id);
-
public Either<User, StorageOperationStatus> saveUserData(User user);
public Either<User, StorageOperationStatus> updateUserData(User user);
@@ -48,11 +46,6 @@ public interface IUserAdminOperation {
public Either<List<User>, ActionStatus> getAllUsersWithRole(String role, String status);
- Either<List<User>, ActionStatus> getAllUsers();
-
public Either<List<Edge>, StorageOperationStatus> getUserPendingTasksList(User user, Map<String, Object> properties);
- public Either<ImmutablePair<User, FunctionalMenuInfo>, ActionStatus> getUserDataWithFunctionalMenu(String userId);
-
- public Either<FunctionalMenuInfo, TitanOperationStatus> createOrUpdateFunctionalMenu(String userId, String newFunctionalMenu);
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java
deleted file mode 100644
index 2a5893951a..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.api;
-
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.model.ComponentInstance;
-
-import java.util.List;
-
-public interface ToscaDefinitionPathCalculator {
-
- List<String> calculateToscaDefinitionPath(ComponentInstance componentInstance, GraphEdge edge);
-
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AllOperationsUtil.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AllOperationsUtil.java
deleted file mode 100644
index c005176238..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AllOperationsUtil.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import org.springframework.stereotype.Component;
-
-@Component("all-operations")
-public class AllOperationsUtil {
-
- @javax.annotation.Resource
- private PropertyOperation propertyOperation;
-
- @javax.annotation.Resource
- private RequirementOperation requirementOperation;
-
- @javax.annotation.Resource
- private CapabilityOperation capabilityOperation;
-
- @javax.annotation.Resource
- private ResourceOperation resourceOperation;
-
- public PropertyOperation getPropertyOperation() {
- return propertyOperation;
- }
-
- public RequirementOperation getRequirementOperation() {
- return requirementOperation;
- }
-
- public CapabilityOperation getCapabilityOperation() {
- return capabilityOperation;
- }
-
- public ResourceOperation getResourceOperation() {
- return resourceOperation;
- }
-
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java
index 1e1c9267e6..d9fe1eea92 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java
@@ -131,24 +131,6 @@ public class ArtifactOperation implements IArtifactOperation {
}
@Override
- public StorageOperationStatus addArifactToComponent(TitanVertex artifactInfo, TitanVertex parentVertex, String label) {
-
- // save logical artifact ref name on edge as property
- Map<String, Object> properties = new HashMap<String, Object>();
- properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), label);
- String groupInfo = (String) titanGenericDao.getProperty(artifactInfo, GraphPropertiesDictionary.ARTIFACT_GROUP_TYPE.getProperty());
- if (groupInfo != null)
- properties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), groupInfo);
- TitanOperationStatus relation = titanGenericDao.createEdge(parentVertex, artifactInfo, GraphEdgeLabels.ARTIFACT_REF, properties);
- if (!relation.equals(TitanOperationStatus.OK)) {
- log.debug("Failed to create relation in graph from id {} to new artifact {}", parentVertex, label);
- return DaoStatusConverter.convertTitanStatusToStorageStatus(relation);
- }
- return StorageOperationStatus.OK;
-
- }
-
- @Override
public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, TitanVertex parentVertex) {
StorageOperationStatus status = addArtifactToGraph(artifactInfo, parentId, type, failIfExist, parentVertex);
@@ -345,156 +327,6 @@ public class ArtifactOperation implements IArtifactOperation {
}
@Override
- public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact( String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, boolean inTransaction){
-
-
- Either<ArtifactData, StorageOperationStatus> status = dissociateAndAssociateHeatEnvArtifact(id, artifactEnvInfo, artifactId, newArtifactId, type, inTransaction);
-
-
- if (status.isRight()) {
- if (false == inTransaction) {
- titanGenericDao.rollback();
- }
- log.debug("Failed to update artifact {} of {} {}. status is {}", artifactId, type.getName(), id, status.right().value());
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "Failed to update artifact " + artifactId + " of " + type.getName() + " " + id + ". status is" + status.right().value(), artifactId,
- String.valueOf(status.right().value()));
- BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactId, String.valueOf(status.right().value()));
- return Either.right(status.right().value());
- } else {
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- ArtifactData artifactData = status.left().value();
-
- ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData);
- log.debug("The returned ArtifactDefintion is {}", artifactDefResult);
- return Either.left(artifactDefResult);
- }
-
- }
-
- private Either<ArtifactData, StorageOperationStatus> dissociateAndAssociateHeatEnvArtifact(String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, boolean inTransaction) {
-
- ArtifactDefinition heatEnvArt = artifactEnvInfo;
- if(heatEnvArt == null ){
- Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither = getHeatEnvByGeneratedFromId(artifactId);
- if (heatEnvEither.isRight()) {
- log.error("No heat env artifact node for id = {} ", artifactId);
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- heatEnvArt = heatEnvEither.left().value();
- }
-
- Either<ArtifactData, StorageOperationStatus> status = updateArtifactOnGraph(heatEnvArt, heatEnvArt.getUniqueId(), type, id);
- if(status.isRight()){
- log.error("Failed to update heat env. status is {}", status.right().value());
- return status;
- }
-
- UniqueIdData generatedFromArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, heatEnvArt.getUniqueId());
- UniqueIdData oldArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId);
-
- Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(generatedFromArtifactNode, oldArtifactNode, GraphEdgeLabels.GENERATED_FROM);
- if (deleteRelation.isRight()) {
- TitanOperationStatus titanStatus = deleteRelation.right().value();
- if (titanStatus == TitanOperationStatus.NOT_FOUND) {
- titanStatus = TitanOperationStatus.INVALID_ID;
- }
- Either.right(titanStatus);
- }
-
- UniqueIdData newArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifactId);
-
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(generatedFromArtifactNode, newArtifactNode, GraphEdgeLabels.GENERATED_FROM, null);
- if (createRelation.isRight()) {
- log.error("Failed to create relation from heat_env {} to heat {}", newArtifactId, generatedFromArtifactNode);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value()));
- }
- return status;
- }
-
- @Override
- public Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinition(ArtifactDefinition artifactInfo, boolean inTransaction) {
- Either<ArtifactData, TitanOperationStatus> status = updateArifactDataDefinition(artifactInfo);
-
- if (status.isRight()) {
- if (false == inTransaction) {
- titanGenericDao.rollback();
- }
- log.debug("Failed to update artifact {}", artifactInfo.getUniqueId());
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "Failed to update artifact " + artifactInfo.getUniqueId() + ". status is" + status.right().value(), artifactInfo.getUniqueId(),
- String.valueOf(status.right().value()));
- BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getUniqueId(), String.valueOf(status.right().value()));
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value()));
- } else {
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- ArtifactData artifactData = status.left().value();
-
- ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData);
- log.debug("The returned ArtifactDefintion is {}", artifactDefResult);
- return Either.left(artifactDefResult);
- }
- }
-
- @Override
- public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, boolean inTransaction) {
-
- updateVersionAndDate(artifactInfo, artifactInfo.getArtifactVersion());
-
- Either<ArtifactData, TitanOperationStatus> status = updateArifactDataDefinition(artifactInfo);
-
- if (status.isRight()) {
- if (false == inTransaction) {
- titanGenericDao.rollback();
- }
- log.debug("Failed to update artifact {}", artifactInfo.getUniqueId());
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "Failed to update artifact " + artifactInfo.getUniqueId() + ". status is" + status.right().value(), artifactInfo.getUniqueId(),
- String.valueOf(status.right().value()));
- BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getUniqueId(), String.valueOf(status.right().value()));
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value()));
- } else {
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- ArtifactData artifactData = status.left().value();
-
- ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData);
- log.debug("The returned ArtifactDefintion is {}" , artifactDefResult);
- return Either.left(artifactDefResult);
- }
- }
-
- @Override
- public Either<ArtifactDefinition, StorageOperationStatus> getHeatEnvByGeneratedFromId(String generatedFromId) {
- String heatEnvId = generatedFromId.concat("env");
- Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither = getArtifactById(heatEnvId, true);
- if (heatEnvEither.isRight()) {
- log.error("No heat env artifact node for id = {} ", heatEnvId);
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- return heatEnvEither;
- }
-
- private Either<ArtifactData, TitanOperationStatus> updateArifactDataDefinition(ArtifactDefinition artifactInfo) {
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- if (graph.isRight()) {
- return Either.right(graph.right().value());
- }
-
- ArtifactData artifactData = new ArtifactData(artifactInfo);
-
- Either<ArtifactData, TitanOperationStatus> status = titanGenericDao.updateNode(artifactData, ArtifactData.class);
-
- if (status.isRight()) {
- return Either.right(status.right().value());
-
- }
- return Either.left(status.left().value());
- }
-
- @Override
public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact, boolean inTransaction) {
Either<ArtifactData, TitanOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact);
@@ -519,10 +351,6 @@ public class ArtifactOperation implements IArtifactOperation {
}
}
- public Either<ArtifactData, StorageOperationStatus> updateToscaArtifactNameOnGraph(ArtifactDefinition artifactInfo, String artifactId, NodeTypeEnum type, String id) {
- return updateArtifactOnGraph(artifactInfo, artifactId, type, id);
- }
-
@SuppressWarnings("null")
private Either<ArtifactData, StorageOperationStatus> updateArtifactOnGraph(ArtifactDefinition artifactInfo, String artifactId, NodeTypeEnum type, String id) {
@@ -740,30 +568,7 @@ public class ArtifactOperation implements IArtifactOperation {
return Either.left(true);
}
- public Either<Integer, StorageOperationStatus> getParentsOfArtifact(String artifactId, NodeTypeEnum type) {
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- if (graph.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
- }
- TitanGraph tGraph = graph.left().value();
- @SuppressWarnings("unchecked")
- Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId).vertices();
- Iterator<TitanVertex> iterator = verticesArtifact.iterator();
- if (!iterator.hasNext()) {
- log.debug("No artifact node for id = {}", artifactId);
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- Vertex artifactV = iterator.next();
- Iterator<Edge> iterEdge = artifactV.edges(Direction.IN, GraphEdgeLabels.ARTIFACT_REF.getProperty());
- int edgeCount = 0;
- while (iterEdge.hasNext()) {
- Edge edge = iterEdge.next();
- ++edgeCount;
- }
- return Either.left(edgeCount);
- }
-
- public Either<ArtifactData, TitanOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) {
+ private Either<ArtifactData, TitanOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) {
Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
if (graph.isRight()) {
return Either.right(graph.right().value());
@@ -928,288 +733,7 @@ public class ArtifactOperation implements IArtifactOperation {
}
- public Either<Map<String, TitanVertex>, StorageOperationStatus> getArtifactsVertecies(String parentId, NodeTypeEnum parentType, boolean inTransaction) {
- Either<Map<String, TitanVertex>, StorageOperationStatus> result = null;
- try {
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- if (graph.isRight()) {
- log.debug("Failed to work with graph {}", graph.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
- }
- TitanGraph tGraph = graph.left().value();
- @SuppressWarnings("unchecked")
- Iterable<TitanVertex> vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices();
- if (vertices == null) {
- log.debug("No nodes for type {} for id = {}", parentType, parentId);
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- return result;
- }
- Iterator<TitanVertex> iterator = vertices.iterator();
-
- Map<String, TitanVertex> artifactMap = new HashMap<String, TitanVertex>();
- while (iterator.hasNext()) {
- Vertex vertex = iterator.next();
- Iterator<Edge> iteratorEdge = vertex.edges(Direction.OUT, GraphEdgeLabels.ARTIFACT_REF.getProperty());
-
- if (iteratorEdge != null) {
-
- while (iteratorEdge.hasNext()) {
- Edge edge = iteratorEdge.next();
-
- TitanVertex artifactV = (TitanVertex) edge.inVertex();
- String label = (String) titanGenericDao.getProperty(artifactV, GraphPropertiesDictionary.ARTIFACT_LABEL.getProperty());
- artifactMap.put(label, artifactV);
- log.debug("Artifact was added to list {}", label);
- }
- }
- }
- result = Either.left(artifactMap);
- return result;
- } finally {
- if (inTransaction == false) {
- if (result == null || result.isRight()) {
- this.titanGenericDao.rollback();
- } else {
- this.titanGenericDao.commit();
- }
-
- }
- }
-
- }
-
- @Override
- public Either<ArtifactDefinition, StorageOperationStatus> getArtifactById(String id, boolean inTransaction) {
- Either<ArtifactDefinition, StorageOperationStatus> result = null;
- try {
- Either<ArtifactData, TitanOperationStatus> artifact = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), id, ArtifactData.class);
- if (artifact.isRight()) {
- if (artifact.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- result = Either.right(StorageOperationStatus.ARTIFACT_NOT_FOUND);
- } else {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(artifact.right().value()));
- }
- return result;
- }
- ArtifactData artifactData = artifact.left().value();
-
- ArtifactDefinition artifactDef = new ArtifactDefinition(artifactData.getArtifactDataDefinition());
- List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>();
- StorageOperationStatus heatParametersStatus = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDef.getUniqueId(), heatParams);
- if (!heatParametersStatus.equals(StorageOperationStatus.OK)) {
- log.debug("failed to get heat parameters for artifact {}", id);
- return Either.right(heatParametersStatus);
- }
- if (!heatParams.isEmpty()) {
- artifactDef.setListHeatParameters(heatParams);
- }
-
- Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> generatedFromArtifact = titanGenericDao.getChild(artifactData.getUniqueIdKey(), (String) artifactData.getUniqueId(), GraphEdgeLabels.GENERATED_FROM,
- NodeTypeEnum.ArtifactRef, ArtifactData.class);
- if (generatedFromArtifact.isLeft()) {
- ImmutablePair<ArtifactData, GraphEdge> pair = generatedFromArtifact.left().value();
- String generatedFromId = (String) pair.left.getUniqueId();
- log.debug("artifact {} is generated from {}.", artifactData.getUniqueId(), generatedFromId);
- artifactDef.setGeneratedFromId(generatedFromId);
- Either<List<HeatParameterDefinition>, StorageOperationStatus> heatParamsForEnv = getHeatParamsForEnv(artifactDef);
- if (heatParamsForEnv.isRight()) {
- log.debug("failed to get heat parameters values for heat artifact {}", artifactDef.getUniqueId());
- return Either.right(heatParamsForEnv.right().value());
- } else {
- artifactDef.setListHeatParameters(heatParamsForEnv.left().value());
- }
- }
-
- result = Either.left(artifactDef);
- return result;
- } finally {
- if (inTransaction == false) {
- if (result == null || result.isRight()) {
- this.titanGenericDao.rollback();
- } else {
- this.titanGenericDao.commit();
- }
-
- }
- }
- }
-
- public Either<List<HeatParameterDefinition>, StorageOperationStatus> getHeatParamsForEnv(ArtifactDefinition heatEnvArtifact) {
-
- List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>();
- StorageOperationStatus heatParametersStatus = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, heatEnvArtifact.getGeneratedFromId(), heatParams);
- if (!heatParametersStatus.equals(StorageOperationStatus.OK)) {
- log.debug("failed to get heat parameters for node {}", heatEnvArtifact.getGeneratedFromId());
- return Either.right(heatParametersStatus);
- }
- if (!heatParams.isEmpty()) {
-
- Map<String, HeatParameterValueData> heatValuesMap = new HashMap<String, HeatParameterValueData>();
- Either<List<ImmutablePair<HeatParameterValueData, GraphEdge>>, TitanOperationStatus> heatEnvValuesWithEdges = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), heatEnvArtifact.getUniqueId(),
- GraphEdgeLabels.PARAMETER_VALUE, NodeTypeEnum.HeatParameterValue, HeatParameterValueData.class);
-
- if (heatEnvValuesWithEdges.isRight() && !heatEnvValuesWithEdges.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- TitanOperationStatus status = heatEnvValuesWithEdges.right().value();
- if (!status.equals(TitanOperationStatus.NOT_FOUND)) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- } else if (heatEnvValuesWithEdges.isLeft()) {
- for (ImmutablePair<HeatParameterValueData, GraphEdge> pair : heatEnvValuesWithEdges.left().value()) {
- HeatParameterValueData parameterValue = pair.left;
- Object heatParameterName = pair.right.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty());
- heatValuesMap.put((String) heatParameterName, parameterValue);
- }
- }
-
- for (HeatParameterDefinition parameter : heatParams) {
- if (parameter.getCurrentValue() != null) {
- if ("number".equals(parameter.getType())) {
- parameter.setDefaultValue(new BigDecimal(parameter.getCurrentValue()).toPlainString());
- } else {
- parameter.setDefaultValue(parameter.getCurrentValue());
- }
- }
- HeatParameterValueData heatParameterValueData = heatValuesMap.get(parameter.getName());
- if (heatParameterValueData != null && heatParameterValueData.getValue() != null) {
- if ("number".equals(parameter.getType())) {
- parameter.setCurrentValue(new BigDecimal(heatParameterValueData.getValue()).toPlainString());
- } else {
- parameter.setCurrentValue(heatParameterValueData.getValue());
- }
- parameter.setUniqueId((String) heatParameterValueData.getUniqueId());
-
- }
- }
- }
-
- return Either.left(heatParams);
-
- }
-
- @Override
- public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, String groupType) {
-
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = null;
- try {
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- if (graph.isRight()) {
- log.debug("Failed to work with graph {}", graph.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
- }
- TitanGraph tGraph = graph.left().value();
- @SuppressWarnings("unchecked")
- Iterable<TitanVertex> vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices();
- if (vertices == null || vertices.iterator() == null || false == vertices.iterator().hasNext()) {
- log.debug("No nodes for type {} for id = {}", parentType, parentId);
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- return result;
- }
-
- Iterator<TitanVertex> iterator = vertices.iterator();
- Vertex vertex = iterator.next();
-
- Map<String, Object> edgeProperties = null;
- if (groupType != null) {
- edgeProperties = new HashMap<>();
- edgeProperties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), groupType);
- }
- Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> childrenByEdgeCriteria = titanGenericDao.getChildrenByEdgeCriteria(vertex, parentId, GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class,
- edgeProperties);
-
- if (childrenByEdgeCriteria.isRight()) {
- TitanOperationStatus status = childrenByEdgeCriteria.right().value();
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- List<ImmutablePair<ArtifactData, GraphEdge>> list = childrenByEdgeCriteria.left().value();
-
- Map<String, ArtifactDefinition> artifactsMap = new HashMap<>();
-
- for (ImmutablePair<ArtifactData, GraphEdge> pair : list) {
- ArtifactData artifactData = pair.getLeft();
- ArtifactDefinition artifactDefinition = new ArtifactDefinition(artifactData.getArtifactDataDefinition());
-
- List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>();
- StorageOperationStatus heatParametersStatus = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefinition.getUniqueId(), heatParams);
- if (!heatParametersStatus.equals(StorageOperationStatus.OK)) {
- log.debug("failed to get heat parameters for node {} {}", parentType.getName(), parentId);
- return Either.right(heatParametersStatus);
- }
- if (!heatParams.isEmpty()) {
- artifactDefinition.setListHeatParameters(heatParams);
- }
-
- Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactDefinition.getUniqueId(), GraphEdgeLabels.GENERATED_FROM,
- NodeTypeEnum.ArtifactRef, ArtifactData.class);
-
- if (getResult.isRight()) {
- TitanOperationStatus status = getResult.right().value();
- if (!status.equals(TitanOperationStatus.NOT_FOUND)) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- } else {
- ImmutablePair<ArtifactData, GraphEdge> immutablePair = getResult.left().value();
- artifactDefinition.setGeneratedFromId((String) immutablePair.left.getUniqueId());
- }
-
- artifactsMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
- log.debug("Artifact {} was added to list ", artifactData.getUniqueId());
- }
-
- result = Either.left(artifactsMap);
- return result;
-
- } finally {
- if (inTransaction == false) {
- if (result == null || result.isRight()) {
- this.titanGenericDao.rollback();
- } else {
- this.titanGenericDao.commit();
- }
-
- }
- }
- }
-
- @Override
- public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String parentId, NodeTypeEnum parentType, boolean failIfExist) {
-
- Either<ArtifactDefinition, StorageOperationStatus> result = null;
- Either<ArtifactDefinition, StorageOperationStatus> heatArtifactOnGraph = addArifactToComponent(artifactHeatEnv, parentId, parentType, failIfExist, true);
- if (heatArtifactOnGraph.isRight()) {
- log.debug("failed to create heat env artifact on graph");
- result = heatArtifactOnGraph;
- return result;
- }
-
- ArtifactDefinition artifactDefinition = heatArtifactOnGraph.left().value();
- // add relation from heatEnv to heat
- UniqueIdData heatData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactHeat.getUniqueId());
- UniqueIdData heatEnvData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactDefinition.getUniqueId());
-
- Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.getRelation(heatEnvData, heatData, GraphEdgeLabels.GENERATED_FROM);
- if (relation.isRight()) {
- // TODO: add error in case of error
- TitanOperationStatus status = relation.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(heatEnvData, heatData, GraphEdgeLabels.GENERATED_FROM, null);
- if (createRelation.isRight()) {
- status = createRelation.right().value();
- log.debug("failed to add relation from heat_env artifact to heat artifact. error: {}", status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- }
- }
-
- artifactDefinition.setGeneratedFromId(artifactHeat.getUniqueId());
- log.trace("heat env artifact added successfuly to resource instance");
- result = Either.left(artifactDefinition);
- return result;
- }
-
- public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion) {
+ private void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion) {
if (oldVesrion == null || oldVesrion.isEmpty())
oldVesrion = "0";
@@ -1240,96 +764,4 @@ public class ArtifactOperation implements IArtifactOperation {
artifactData.setArtifactVersion(String.valueOf(newVersion));
}
- @Override
- public Either<ArtifactDefinition, StorageOperationStatus> getHeatArtifactByHeatEnvId(String heatEnvId, boolean inTransaction) {
-
- Either<ArtifactDefinition, StorageOperationStatus> result = null;
- try {
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- if (graph.isRight()) {
- log.debug("Failed to work with graph {}", graph.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
- }
- TitanGraph tGraph = graph.left().value();
- @SuppressWarnings("unchecked")
- Iterable<TitanVertex> vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), heatEnvId).vertices();
- if (vertices == null || vertices.iterator() == null || false == vertices.iterator().hasNext()) {
- log.debug("No nodes for type {} for id = {}", NodeTypeEnum.ArtifactRef, heatEnvId);
- result = Either.right(StorageOperationStatus.INVALID_ID);
- return result;
- }
-
- Iterator<TitanVertex> iterator = vertices.iterator();
- Vertex vertex = iterator.next();
-
- Map<String, Object> edgeProperties = null;
- Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> childrenByEdgeCriteria = titanGenericDao.getChildrenByEdgeCriteria(vertex, heatEnvId, GraphEdgeLabels.GENERATED_FROM, NodeTypeEnum.ArtifactRef, ArtifactData.class,
- edgeProperties);
-
- if (childrenByEdgeCriteria.isRight()) {
- TitanOperationStatus status = childrenByEdgeCriteria.right().value();
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- List<ImmutablePair<ArtifactData, GraphEdge>> list = childrenByEdgeCriteria.left().value();
-
- if (list == null || list.isEmpty() == true) {
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
-
- if (list.size() > 1) {
- return Either.right(StorageOperationStatus.INVALID_ID);
- }
-
- ImmutablePair<ArtifactData, GraphEdge> immutablePair = list.get(0);
-
- ArtifactDefinition artifactDefinition = new ArtifactDefinition(immutablePair.left.getArtifactDataDefinition());
-
- log.debug("The artifact {} was generated from artifact {}", heatEnvId, artifactDefinition);
-
- result = Either.left(artifactDefinition);
- return result;
-
- } finally {
- if (inTransaction == false) {
- if (result == null || result.isRight()) {
- this.titanGenericDao.rollback();
- } else {
- this.titanGenericDao.commit();
- }
-
- }
- }
- }
-
- @Override
- public Either<ArtifactData, StorageOperationStatus> getLatestArtifactDataByArtifactUUID(String artifactUUID, boolean inTransaction) {
- Either<ArtifactData, StorageOperationStatus> result = null;
- try {
- NodeTypeEnum nodeType = NodeTypeEnum.ArtifactRef;
- Map<String, Object> propertiesToMatch = new HashMap<>();
- propertiesToMatch.put(GraphPropertiesDictionary.ARTIFACT_UUID.getProperty(), artifactUUID);
- Either<List<ArtifactData>, TitanOperationStatus> getArtifactEither = titanGenericDao.getByCriteria(nodeType, propertiesToMatch, ArtifactData.class);
- if (getArtifactEither.isRight()) {
- log.debug("Couldn't fetch artifact data for artifact with uuid {}, error: {}", nodeType, getArtifactEither.right().value());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getArtifactEither.right().value()));
- } else {
- List<ArtifactData> artifacts = getArtifactEither.left().value();
- ArtifactData latestArtifact = artifacts.size() == 1 ? artifacts.get(0)
- : artifacts.stream().max((a1, a2) -> Double.compare(Double.parseDouble(a1.getArtifactDataDefinition().getArtifactVersion()), Double.parseDouble(a2.getArtifactDataDefinition().getArtifactVersion()))).get();
- result = Either.left(latestArtifact);
- }
- return result;
- } finally {
- if (!inTransaction) {
- if (result == null || result.isRight()) {
- this.titanGenericDao.rollback();
- } else {
- this.titanGenericDao.commit();
- }
- }
- }
- }
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java
deleted file mode 100644
index 279aab667c..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java
+++ /dev/null
@@ -1,461 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
-import java.util.function.Consumer;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.operations.api.IAttributeOperation;
-import org.openecomp.sdc.be.model.operations.api.IPropertyOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.resources.data.AttributeData;
-import org.openecomp.sdc.be.resources.data.AttributeValueData;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-/**
- * Class For Data Model Logic Relevant For Attributes
- *
- * @author mshitrit
- *
- */
-@Component("attribute-operation")
-public class AttributeOperation extends AbstractOperation implements IAttributeOperation {
- private static Logger log = LoggerFactory.getLogger(AttributeOperation.class.getName());
- @Autowired
- private IPropertyOperation propertyOperation;
-
- /**
- *
- * Add attribute to graph.
- *
- * 1. Add attribute node
- *
- * 2. Add edge between the former node to its parent(if exists)
- *
- * 3. Add property node and associate it to the node created at #1. (per property & if exists)
- *
- * @param attributeDefinition
- * @return
- */
- private Either<AttributeData, TitanOperationStatus> addAttributeToNodeType(PropertyDefinition attributeDefinition, NodeTypeEnum nodeType, String nodeUniqueId) {
- String attUniqueId = UniqueIdBuilder.buildAttributeUid(nodeUniqueId, attributeDefinition.getName());
- Supplier<AttributeData> dataBuilder = () -> buildAttributeData(attributeDefinition, attUniqueId);
- Supplier<String> defNameGenerator = () -> "Attribute : " + attributeDefinition.getName();
-
- return addDefinitionToNodeType(attributeDefinition, nodeType, nodeUniqueId, GraphEdgeLabels.ATTRIBUTE, dataBuilder, defNameGenerator);
-
- }
-
- private TitanOperationStatus addAttributeToNodeType(TitanVertex metadataVertex, PropertyDefinition attributeDefinition, NodeTypeEnum nodeType, String nodeUniqueId) {
- String attUniqueId = UniqueIdBuilder.buildAttributeUid(nodeUniqueId, attributeDefinition.getName());
- Supplier<AttributeData> dataBuilder = () -> buildAttributeData(attributeDefinition, attUniqueId);
- Supplier<String> defNameGenerator = () -> "Attribute : " + attributeDefinition.getName();
-
- return addDefinitionToNodeType(metadataVertex, attributeDefinition, nodeType, nodeUniqueId, GraphEdgeLabels.ATTRIBUTE, dataBuilder, defNameGenerator);
-
- }
-
- private AttributeData buildAttributeData(PropertyDefinition attributeDefinition, String attUniqueId) {
- attributeDefinition.setUniqueId(attUniqueId);
- return new AttributeData(attributeDefinition);
- }
-
- @Override
- public Either<AttributeData, StorageOperationStatus> deleteAttribute(String attributeId) {
- Either<AttributeData, TitanOperationStatus> either = deleteAttributeFromGraph(attributeId);
- if (either.isRight()) {
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value());
- return Either.right(storageStatus);
- }
- return Either.left(either.left().value());
- }
-
- @Override
- public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllAttributeAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) {
- Wrapper<TitanOperationStatus> errorWrapper;
- List<PropertyDefinition> attributes = new ArrayList<>();
- TitanOperationStatus findAllResourceAttribues = findNodeNonInheretedAttribues(uniqueId, NodeTypeEnum.Resource, attributes);
- errorWrapper = (findAllResourceAttribues != TitanOperationStatus.OK) ? new Wrapper<>(findAllResourceAttribues) : new Wrapper<>();
-
- if (errorWrapper.isEmpty()) {
- for (PropertyDefinition attDef : attributes) {
- log.debug("Before deleting attribute from graph {}", attDef.getUniqueId());
- Either<AttributeData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Attribute), attDef.getUniqueId(), AttributeData.class);
- if (deleteNode.isRight()) {
- errorWrapper.setInnerElement(deleteNode.right().value());
- break;
- }
- }
- }
-
- if (errorWrapper.isEmpty()) {
- Map<String, PropertyDefinition> attributesMap = attributes.stream().collect(Collectors.toMap(e -> e.getName(), e -> e));
- return Either.left(attributesMap);
- } else {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(errorWrapper.getInnerElement()));
- }
-
- }
-
- private Either<AttributeData, TitanOperationStatus> deleteAttributeFromGraph(String attributeId) {
- log.debug("Before deleting attribute from graph {}", attributeId);
- return titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Attribute), attributeId, AttributeData.class);
- }
-
- @Override
- public TitanOperationStatus addAttributesToGraph(TitanVertex metadataVertex, Map<String, PropertyDefinition> attributes, String resourceId, Map<String, DataTypeDefinition> dataTypes) {
- TitanOperationStatus titanStatus = TitanOperationStatus.OK;
- for (PropertyDefinition attribute : attributes.values()) {
- TitanOperationStatus eitherAddAttribute = addAttributeToGraphByVertex(metadataVertex, attribute, resourceId, dataTypes);
- if (!eitherAddAttribute.equals(TitanOperationStatus.OK)) {
- titanStatus = eitherAddAttribute;
- break;
- }
- }
- return titanStatus;
- }
-
- @Override
- public Either<List<ComponentInstanceProperty>, TitanOperationStatus> getAllAttributesOfResourceInstance(ComponentInstance compInstance) {
-
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> result;
-
- Either<List<ImmutablePair<AttributeValueData, GraphEdge>>, TitanOperationStatus> attributeImplNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), compInstance.getUniqueId(),
- GraphEdgeLabels.ATTRIBUTE_VALUE, NodeTypeEnum.AttributeValue, AttributeValueData.class);
-
- // Build From Resource
- if (attributeImplNodes.isRight() && attributeImplNodes.right().value() == TitanOperationStatus.NOT_FOUND) {
- result = getAttributesFromResource(compInstance);
- }
- // Build From Instance
- else if (attributeImplNodes.isLeft()) {
- List<ImmutablePair<AttributeValueData, GraphEdge>> attributesFromRI = attributeImplNodes.left().value();
- result = mergeAttributesResults(getAttributesFromResource(compInstance), convertToComponentInstanceAttribute(attributesFromRI));
- }
- // Error
- else {
- TitanOperationStatus status = attributeImplNodes.right().value();
- result = Either.right(status);
- }
-
- return result;
- }
-
- private Either<List<ComponentInstanceProperty>, TitanOperationStatus> mergeAttributesResults(Either<List<ComponentInstanceProperty>, TitanOperationStatus> eitherAttributesThatDoesNotExistOnRI,
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> eitherAttributesThatExistOnRI) {
-
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> result;
- if (eitherAttributesThatExistOnRI.isRight()) {
- result = Either.right(eitherAttributesThatExistOnRI.right().value());
- } else if (eitherAttributesThatDoesNotExistOnRI.isRight()) {
- result = Either.right(eitherAttributesThatDoesNotExistOnRI.right().value());
- } else {
- final List<ComponentInstanceProperty> attributesThatExistOnRI = eitherAttributesThatExistOnRI.left().value();
- final List<ComponentInstanceProperty> attributesThatDoesNotExistOnRI = eitherAttributesThatDoesNotExistOnRI.left().value();
- Set<String> attributesIdThatExistOnRI = attributesThatExistOnRI.stream().map(e -> e.getUniqueId()).collect(Collectors.toSet());
- // Attributes From The Resource Without attributes that also exist
- // on the instance
- Stream<ComponentInstanceProperty> filterAttributesThatDoesNotExistOnRI = attributesThatDoesNotExistOnRI.stream().filter(e -> !attributesIdThatExistOnRI.contains(e.getUniqueId()));
- // Add Fields From Resource Attributes
- fillAttributeInfoFromResource(attributesThatExistOnRI, attributesThatDoesNotExistOnRI);
- // Adding the Attributes on the instance for the full list
- List<ComponentInstanceProperty> mergedList = Stream.concat(filterAttributesThatDoesNotExistOnRI, attributesThatExistOnRI.stream()).collect(Collectors.toList());
- result = Either.left(mergedList);
- }
- return result;
- }
-
- private void fillAttributeInfoFromResource(List<ComponentInstanceProperty> attributesThatExistOnRI, List<ComponentInstanceProperty> attributesThatDoesNotExistOnRI) {
- attributesThatExistOnRI.stream()
- .forEach(e -> addAttributeInfo(e,
- // Finds the same attribute in the resource
- attributesThatDoesNotExistOnRI.stream().filter(e2 -> e2.getUniqueId().equals(e.getUniqueId())).findAny().get()));
-
- }
-
- private void addAttributeInfo(ComponentInstanceProperty attributeFromRI, ComponentInstanceProperty attributeFromResource) {
- attributeFromRI.setName(attributeFromResource.getName());
- attributeFromRI.setDescription(attributeFromResource.getDescription());
- attributeFromRI.setDefaultValue(attributeFromResource.getDefaultValue());
- attributeFromRI.setStatus(attributeFromResource.getStatus());
- attributeFromRI.setSchema(attributeFromResource.getSchema());
- if (StringUtils.isEmpty(attributeFromRI.getValue())) {
- attributeFromRI.setValue(attributeFromResource.getDefaultValue());
- }
- }
-
- private Either<List<ComponentInstanceProperty>, TitanOperationStatus> getAttributesFromResource(ComponentInstance compInstance) {
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> result;
- List<PropertyDefinition> attributes = new ArrayList<>();
- // Attributes does not exist on Ri - fetch them from resource
- TitanOperationStatus findAllResourceAttribues = findAllResourceAttributesRecursively(compInstance.getComponentUid(), attributes);
- if (findAllResourceAttribues != TitanOperationStatus.OK) {
- result = Either.right(findAllResourceAttribues);
- } else {
- List<ComponentInstanceProperty> buildAttInstanceFromResource = attributes.stream().map(attDef -> new ComponentInstanceProperty(false, attDef, null)).collect(Collectors.toList());
-
- // Set Value to be default value in case it is empty
- Consumer<ComponentInstanceProperty> valueSetter = att -> {
- if (StringUtils.isEmpty(att.getValue())) {
- att.setValue(att.getDefaultValue());
- }
- };
- buildAttInstanceFromResource.stream().forEach(valueSetter);
-
- result = Either.left(buildAttInstanceFromResource);
- }
- return result;
- }
-
- private Either<List<ComponentInstanceProperty>, TitanOperationStatus> convertToComponentInstanceAttribute(List<ImmutablePair<AttributeValueData, GraphEdge>> list) {
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> result = null;
- List<ComponentInstanceProperty> componentInstanceAttribute = new ArrayList<>();
- for (ImmutablePair<AttributeValueData, GraphEdge> attributeValue : list) {
- AttributeValueData attributeValueData = attributeValue.getLeft();
- String attributeValueUid = attributeValueData.getUniqueId();
-
- Either<ImmutablePair<AttributeData, GraphEdge>, TitanOperationStatus> attributeDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.AttributeValue), attributeValueUid, GraphEdgeLabels.ATTRIBUTE_IMPL,
- NodeTypeEnum.Attribute, AttributeData.class);
-
- if (attributeDefRes.isRight()) {
- TitanOperationStatus status = attributeDefRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- result = Either.right(status);
- break;
- } else {
- ImmutablePair<AttributeData, GraphEdge> attributeDefPair = attributeDefRes.left().value();
- String attributeUniqueId = attributeDefPair.left.getUniqueId();
-
- ComponentInstanceProperty resourceInstanceAttribute = new ComponentInstanceProperty();
- // set attribute original unique id
- resourceInstanceAttribute.setUniqueId(attributeUniqueId);
- // set hidden
- resourceInstanceAttribute.setHidden(attributeValueData.isHidden());
- // set value
- resourceInstanceAttribute.setValue(attributeValueData.getValue());
- // set property value unique id
- resourceInstanceAttribute.setValueUniqueUid(attributeValueUid);
-
- resourceInstanceAttribute.setType(attributeValueData.getType());
-
- componentInstanceAttribute.add(resourceInstanceAttribute);
- }
-
- }
- if (result == null) {
- result = Either.left(componentInstanceAttribute);
- }
- return result;
- }
-
- /**
- * fetch all attributes under a given resource(includes its parents' resources)
- *
- * @param resourceId
- * @param attributes
- * @return
- */
- @Override
- public TitanOperationStatus findAllResourceAttributesRecursively(String resourceId, List<PropertyDefinition> attributes) {
- final NodeElementFetcher<PropertyDefinition> singleNodeFetcher = (resourceIdParam, attributesParam) -> findNodeNonInheretedAttribues(resourceIdParam, NodeTypeEnum.Resource, attributesParam);
- return findAllResourceElementsDefinitionRecursively(resourceId, attributes, singleNodeFetcher);
-
- }
-
- @Override
- public TitanOperationStatus findNodeNonInheretedAttribues(String uniqueId, NodeTypeEnum nodeType, List<PropertyDefinition> attributes) {
- Either<List<ImmutablePair<AttributeData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.ATTRIBUTE, NodeTypeEnum.Attribute,
- AttributeData.class);
-
- if (childrenNodes.isRight()) {
- TitanOperationStatus status = childrenNodes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.OK;
- }
- return status;
- }
-
- List<ImmutablePair<AttributeData, GraphEdge>> values = childrenNodes.left().value();
- if (values != null) {
-
- for (ImmutablePair<AttributeData, GraphEdge> immutablePair : values) {
- AttributeData attData = immutablePair.getLeft();
- String attributeName = attData.getAttributeDataDefinition().getName();
-
- log.debug("Attribute {} is associated to node {}", attributeName, uniqueId);
- AttributeData attributeData = immutablePair.getKey();
- PropertyDefinition attributeDefinition = this.convertAttributeDataToAttributeDefinition(attributeData, attributeName, uniqueId);
-
- attributes.add(attributeDefinition);
-
- log.trace("findAttributesOfNode - property {} associated to node {}", attributeDefinition, uniqueId);
- }
-
- }
-
- return TitanOperationStatus.OK;
- }
-
- @Override
- public PropertyDefinition convertAttributeDataToAttributeDefinition(AttributeData attributeData, String attributeName, String resourceId) {
- log.debug("The object returned after create attribute is {}", attributeData);
- PropertyDefinition attributeDefResult = new PropertyDefinition(attributeData.getAttributeDataDefinition());
- attributeDefResult.setName(attributeName);
- attributeDefResult.setParentUniqueId(resourceId);
- return attributeDefResult;
- }
-
- @Override
- public Either<AttributeData, StorageOperationStatus> addAttribute(PropertyDefinition attributeDefinition, String resourceId) {
-
- Either<AttributeData, StorageOperationStatus> eitherResult;
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- log.debug("Cannot find any data type. Status is {}.", status);
- eitherResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- } else {
- Either<AttributeData, TitanOperationStatus> either = addAttributeToGraph(attributeDefinition, resourceId, allDataTypes.left().value());
- if (either.isRight()) {
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value());
- eitherResult = Either.right(storageStatus);
- } else {
- eitherResult = Either.left(either.left().value());
- }
- }
- return eitherResult;
- }
-
- @Override
- public Either<AttributeData, StorageOperationStatus> updateAttribute(String attributeId, PropertyDefinition newAttDef, Map<String, DataTypeDefinition> dataTypes) {
-
- StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(newAttDef, dataTypes);
- if (validateAndUpdateAttribute != StorageOperationStatus.OK) {
- return Either.right(validateAndUpdateAttribute);
- }
-
- Either<AttributeData, TitanOperationStatus> either = updateAttributeFromGraph(attributeId, newAttDef);
- if (either.isRight()) {
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value());
- return Either.right(storageStatus);
- }
- return Either.left(either.left().value());
- }
-
- private Either<AttributeData, TitanOperationStatus> updateAttributeFromGraph(String attributeId, PropertyDefinition attributeDefenition) {
- log.debug("Before updating attribute on graph {}", attributeId);
-
- // get the original property data
- Either<AttributeData, TitanOperationStatus> eitherAttribute = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Attribute), attributeId, AttributeData.class);
- if (eitherAttribute.isRight()) {
- log.debug("Problem while get Attribute with id {}. Reason - {}", attributeId, eitherAttribute.right().value().name());
- return Either.right(eitherAttribute.right().value());
- }
- AttributeData orgAttributeData = eitherAttribute.left().value();
- PropertyDataDefinition orgAttributeDataDefinition = orgAttributeData.getAttributeDataDefinition();
-
- // create new property data to update
- AttributeData newAttributeData = new AttributeData();
- newAttributeData.setAttributeDataDefinition(attributeDefenition);
- PropertyDataDefinition newAttributeDataDefinition = newAttributeData.getAttributeDataDefinition();
-
- // update the original property data with new values
- if (!Objects.equals(orgAttributeDataDefinition.getDefaultValue(), newAttributeDataDefinition.getDefaultValue())) {
- orgAttributeDataDefinition.setDefaultValue(newAttributeDataDefinition.getDefaultValue());
- }
-
- if (!Objects.equals(orgAttributeDataDefinition.getDescription(), newAttributeDataDefinition.getDescription())) {
- orgAttributeDataDefinition.setDescription(newAttributeDataDefinition.getDescription());
- }
-
- if (!Objects.equals(orgAttributeDataDefinition.getType(), newAttributeDataDefinition.getType())) {
- orgAttributeDataDefinition.setType(newAttributeDataDefinition.getType());
- }
-
- orgAttributeDataDefinition.setSchema(newAttributeDataDefinition.getSchema());
-
- return titanGenericDao.updateNode(orgAttributeData, AttributeData.class);
- }
-
- @Override
- public ComponentInstanceProperty buildResourceInstanceAttribute(AttributeValueData attributeValueData, ComponentInstanceProperty resourceInstanceAttribute) {
-
- Boolean hidden = attributeValueData.isHidden();
- String uid = attributeValueData.getUniqueId();
- return new ComponentInstanceProperty(hidden, resourceInstanceAttribute, uid);
- }
-
- @Override
- public Either<AttributeData, TitanOperationStatus> addAttributeToGraph(PropertyDefinition attribute, String resourceId, Map<String, DataTypeDefinition> dataTypes) {
- Either<AttributeData, TitanOperationStatus> eitherResult;
- StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(attribute, dataTypes);
- if (validateAndUpdateAttribute != StorageOperationStatus.OK) {
- log.error("Attribute {} is invalid. Status is {}", attribute, validateAndUpdateAttribute);
- eitherResult = Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- } else {
- eitherResult = addAttributeToNodeType(attribute, NodeTypeEnum.Resource, resourceId);
-
- }
- return eitherResult;
- }
-
- @Override
- public TitanOperationStatus addAttributeToGraphByVertex(TitanVertex metadataVertex, PropertyDefinition attribute, String resourceId, Map<String, DataTypeDefinition> dataTypes) {
- StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(attribute, dataTypes);
- TitanOperationStatus result;
- if (validateAndUpdateAttribute != StorageOperationStatus.OK) {
- log.error("Attribute {} is invalid. Status is {}", attribute, validateAndUpdateAttribute);
- result = TitanOperationStatus.ILLEGAL_ARGUMENT;
- } else {
- result = addAttributeToNodeType(metadataVertex, attribute, NodeTypeEnum.Resource, resourceId);
-
- }
- return result;
- }
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java
deleted file mode 100644
index 818089feee..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java
+++ /dev/null
@@ -1,1170 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.operations.api.ICapabilityInstanceOperation;
-import org.openecomp.sdc.be.resources.data.CapabilityData;
-import org.openecomp.sdc.be.resources.data.CapabilityInstData;
-import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
-import org.openecomp.sdc.be.resources.data.PropertyData;
-import org.openecomp.sdc.be.resources.data.PropertyValueData;
-import org.openecomp.sdc.be.resources.data.UniqueIdData;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-/**
- * public class CapabilityInstanceOperation provides methods for CRUD operations for CapabilityInstance on component instance level
- *
- * @author ns019t
- *
- */
-@Component("capability-instance-operation")
-public class CapabilityInstanceOperation extends AbstractOperation implements ICapabilityInstanceOperation {
-
- private static Logger log = LoggerFactory.getLogger(CapabilityOperation.class.getName());
-
- @Autowired
- private PropertyOperation propertyOperation;
-
- @Autowired
- private CapabilityOperation capabilityOperation;
-
- /**
- * create capability instance of capability with property values for resource instance
- *
- * @param resourceInstanceId
- * @param capabilityId
- * @param propertyValues
- * @param validateCapabilityInstExistence
- * @param capabilityName
- * @return
- */
- @Override
- public Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(String resourceInstanceId, String capabilityId, String capabilityName,
- List<ComponentInstanceProperty> propertyValues, boolean validateCapabilityInstExistence) {
- Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>();
- Wrapper<CapabilityData> overrideCapabilityDataWrapper = new Wrapper<>();
- Wrapper<CapabilityDefinition> overrideCapabilityDefinitionWrapper = new Wrapper<>();
- Either<CapabilityInstData, TitanOperationStatus> createCapabilityRes = null;
- CapabilityInstData createdCapabilityInstance = null;
-
- Wrapper<Map<String, PropertyDefinition>> defaultPropertiesWrapper = new Wrapper<>();
- Either<ImmutablePair<CapabilityData, GraphEdge>, TitanOperationStatus> getCapabilityRes = null;
- Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes = null;
- Either<List<PropertyValueData>, TitanOperationStatus> addPropertyValuesRes = null;
- Wrapper<String> createdCapabilityInstanceIdWrapper = new Wrapper<>();
- if (validateCapabilityInstExistence) {
- validateCapabilityInstanceExistence(resourceInstanceId, capabilityId, errorWrapper);
- }
- if (errorWrapper.isEmpty()) {
- getCapabilityRes = getCapabilitiesOfResourceInstance(resourceInstanceId, capabilityId, capabilityName, errorWrapper);
- }
- if (errorWrapper.isEmpty()) {
- getCapabilityDefinitionRes = getCapabiityDefinition(resourceInstanceId, capabilityId, errorWrapper, overrideCapabilityDataWrapper, getCapabilityRes);
- }
- if (errorWrapper.isEmpty()) {
- createCapabilityRes = createCapabilityInstanceOnGraph(resourceInstanceId, capabilityId, errorWrapper, overrideCapabilityDataWrapper, overrideCapabilityDefinitionWrapper, getCapabilityDefinitionRes);
- }
- if (errorWrapper.isEmpty() && overrideCapabilityDefinitionWrapper.getInnerElement().getProperties() != null) {
- createdCapabilityInstance = validateCapabilityInstanceProperties(resourceInstanceId, propertyValues, errorWrapper, overrideCapabilityDefinitionWrapper, createCapabilityRes, defaultPropertiesWrapper, createdCapabilityInstanceIdWrapper);
- }
- if (errorWrapper.isEmpty()) {
- addPropertyValuesRes = addPropertyValueToCapabilityInstance(resourceInstanceId, propertyValues, errorWrapper, createCapabilityRes, defaultPropertiesWrapper, createdCapabilityInstanceIdWrapper);
- }
- Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> result;
- if (errorWrapper.isEmpty()) {
- Map<CapabilityInstData, List<PropertyValueData>> resultMap = new HashMap<>();
- resultMap.put(createdCapabilityInstance, addPropertyValuesRes.left().value());
- result = Either.left(resultMap);
- } else {
- result = Either.right(errorWrapper.getInnerElement());
- }
- return result;
- }
-
- @Override
- public TitanOperationStatus createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(TitanVertex resourceInstanceVertex, String resourceInstanceId, String capabilityId, String capabilityName,
- List<ComponentInstanceProperty> propertyValues, boolean validateCapabilityInstExistence) {
- Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>();
- Wrapper<TitanVertex> overrideCapabilityDataWrapper = new Wrapper<>();
- Wrapper<CapabilityDefinition> overrideCapabilityDefinitionWrapper = new Wrapper<>();
- Either<TitanVertex, TitanOperationStatus> createCapabilityRes = null;
- TitanVertex createdCapabilityInstance = null;
-
- Wrapper<Map<String, PropertyDefinition>> defaultPropertiesWrapper = new Wrapper<>();
- Either<ImmutablePair<TitanVertex, Edge>, TitanOperationStatus> getCapabilityRes = null;
- Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes = null;
- TitanOperationStatus addPropertyValuesRes = null;
- Wrapper<String> createdCapabilityInstanceIdWrapper = new Wrapper<>();
- if (validateCapabilityInstExistence) {
- validateCapabilityInstanceExistence(resourceInstanceVertex, resourceInstanceId, capabilityId, errorWrapper);
- }
- if (errorWrapper.isEmpty()) {
- getCapabilityRes = getCapabilitiesOfResourceInstance(resourceInstanceVertex, resourceInstanceId, capabilityId, capabilityName, errorWrapper);
- }
- if (errorWrapper.isEmpty()) {
- getCapabilityDefinitionRes = getCapabiityDefinitionByVertex(resourceInstanceId, capabilityId, errorWrapper, overrideCapabilityDataWrapper, getCapabilityRes);
- }
- if (errorWrapper.isEmpty()) {
- createCapabilityRes = createCapabilityInstanceOnGraphByVertex(resourceInstanceVertex, resourceInstanceId, capabilityId, errorWrapper, overrideCapabilityDataWrapper, overrideCapabilityDefinitionWrapper, getCapabilityDefinitionRes);
- }
- if (errorWrapper.isEmpty() && overrideCapabilityDefinitionWrapper.getInnerElement().getProperties() != null) {
- createdCapabilityInstance = validateCapabilityInstancePropertiesByVertex(resourceInstanceId, propertyValues, errorWrapper, overrideCapabilityDefinitionWrapper, createCapabilityRes.left().value(), defaultPropertiesWrapper,
- createdCapabilityInstanceIdWrapper);
- }
- if (errorWrapper.isEmpty()) {
- addPropertyValuesRes = addPropertyValueToCapabilityInstanceByVertex(resourceInstanceId, propertyValues, errorWrapper, createCapabilityRes, defaultPropertiesWrapper, createdCapabilityInstanceIdWrapper);
- }
-
- return addPropertyValuesRes;
- }
-
- private Either<List<PropertyValueData>, TitanOperationStatus> addPropertyValueToCapabilityInstance(String resourceInstanceId, List<ComponentInstanceProperty> propertyValues, Wrapper<TitanOperationStatus> errorWrapper,
- Either<CapabilityInstData, TitanOperationStatus> createCapabilityRes, Wrapper<Map<String, PropertyDefinition>> defaultPropertiesWrapper, Wrapper<String> createdCapabilityInstanceIdWrapper) {
- Either<List<PropertyValueData>, TitanOperationStatus> addPropertyValuesRes;
- log.debug("Before adding property values to capability instance {}.",createdCapabilityInstanceIdWrapper.getInnerElement());
- addPropertyValuesRes = addPropertyValuesToCapabilityInstance(createCapabilityRes.left().value(), propertyValues, defaultPropertiesWrapper.getInnerElement());
- if (addPropertyValuesRes.isRight()) {
- errorWrapper.setInnerElement(addPropertyValuesRes.right().value());
- log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement());
- }
- log.debug("After adding property values to capability instance {}. status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement());
- return addPropertyValuesRes;
- }
-
- private TitanOperationStatus addPropertyValueToCapabilityInstanceByVertex(String resourceInstanceId, List<ComponentInstanceProperty> propertyValues, Wrapper<TitanOperationStatus> errorWrapper,
- Either<TitanVertex, TitanOperationStatus> createCapabilityRes, Wrapper<Map<String, PropertyDefinition>> defaultPropertiesWrapper, Wrapper<String> createdCapabilityInstanceIdWrapper) {
- log.trace("Before adding property values to capability instance {}", createdCapabilityInstanceIdWrapper.getInnerElement());
- TitanOperationStatus addPropertyValuesRes = addPropertyValuesToCapabilityInstance(createCapabilityRes.left().value(), propertyValues, defaultPropertiesWrapper.getInnerElement());
- if (!addPropertyValuesRes.equals(TitanOperationStatus.OK)) {
- errorWrapper.setInnerElement(addPropertyValuesRes);
- log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement());
- }
- log.trace("After adding property values to capability instance {}. status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement());
- return addPropertyValuesRes;
- }
-
- private CapabilityInstData validateCapabilityInstanceProperties(String resourceInstanceId, List<ComponentInstanceProperty> propertyValues, Wrapper<TitanOperationStatus> errorWrapper,
- Wrapper<CapabilityDefinition> overrideCapabilityDefinitionWrapper, Either<CapabilityInstData, TitanOperationStatus> createCapabilityRes, Wrapper<Map<String, PropertyDefinition>> defaultPropertiesWrapper,
- Wrapper<String> createdCapabilityInstanceIdWrapper) {
- CapabilityInstData createdCapabilityInstance;
- createdCapabilityInstance = createCapabilityRes.left().value();
- createdCapabilityInstanceIdWrapper.setInnerElement(createdCapabilityInstance.getUniqueId());
- Map<String, PropertyDefinition> defaultProperties = overrideCapabilityDefinitionWrapper.getInnerElement().getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
- defaultPropertiesWrapper.setInnerElement(defaultProperties);
- log.debug("Before validating property values of capability instance {}",createdCapabilityInstanceIdWrapper.getInnerElement());
- Either<Boolean, TitanOperationStatus> result = validateCapabilityInstanceProperties(defaultProperties, propertyValues);
- if (result.isRight()) {
- errorWrapper.setInnerElement(result.right().value());
- log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement());
- }
- log.debug("After validating property values of capability instance {}. status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement());
- return createdCapabilityInstance;
- }
-
- private TitanVertex validateCapabilityInstancePropertiesByVertex(String resourceInstanceId, List<ComponentInstanceProperty> propertyValues, Wrapper<TitanOperationStatus> errorWrapper,
- Wrapper<CapabilityDefinition> overrideCapabilityDefinitionWrapper, TitanVertex createCapabilityRes, Wrapper<Map<String, PropertyDefinition>> defaultPropertiesWrapper, Wrapper<String> createdCapabilityInstanceIdWrapper) {
-
- String id = (String) titanGenericDao.getProperty(createCapabilityRes, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- createdCapabilityInstanceIdWrapper.setInnerElement(id);
- Map<String, PropertyDefinition> defaultProperties = overrideCapabilityDefinitionWrapper.getInnerElement().getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
- defaultPropertiesWrapper.setInnerElement(defaultProperties);
- log.trace("Before validating property values of capability instance {}", createdCapabilityInstanceIdWrapper.getInnerElement());
- Either<Boolean, TitanOperationStatus> result = validateCapabilityInstanceProperties(defaultProperties, propertyValues);
- if (result.isRight()) {
- errorWrapper.setInnerElement(result.right().value());
- log.debug("Failed to add properties to capability instance {} of resource instance {}, status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement());
- }
- log.trace("After validating property values of capability instance {}, status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement());
- return createCapabilityRes;
- }
-
- private Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceOnGraph(String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper, Wrapper<CapabilityData> overrideCapabilityDataWrapper,
- Wrapper<CapabilityDefinition> overrideCapabilityDefinitionWrapper, Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes) {
- Either<CapabilityInstData, TitanOperationStatus> createCapabilityRes;
- log.debug("Before creating capability instance of capability {} on graph.", capabilityId);
- overrideCapabilityDefinitionWrapper.setInnerElement(getCapabilityDefinitionRes.left().value());
- CapabilityInstData capabilityInstance = buildCapabilityInstanceData(resourceInstanceId, overrideCapabilityDefinitionWrapper.getInnerElement());
- createCapabilityRes = createCapabilityInstanceOnGraph(resourceInstanceId, overrideCapabilityDataWrapper.getInnerElement(), capabilityInstance);
- if (createCapabilityRes.isRight()) {
- errorWrapper.setInnerElement(createCapabilityRes.right().value());
- log.debug("Failed to create capability instance of capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- }
- log.debug("After creating capability instance of capability {} on graph, status is {}", capabilityId, errorWrapper.getInnerElement());
- return createCapabilityRes;
- }
-
- private Either<TitanVertex, TitanOperationStatus> createCapabilityInstanceOnGraphByVertex(TitanVertex riVertex, String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper,
- Wrapper<TitanVertex> overrideCapabilityDataWrapper, Wrapper<CapabilityDefinition> overrideCapabilityDefinitionWrapper, Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes) {
- Either<TitanVertex, TitanOperationStatus> createCapabilityRes;
- log.trace("Before creating capability instance of capability {} on graph", capabilityId);
- overrideCapabilityDefinitionWrapper.setInnerElement(getCapabilityDefinitionRes.left().value());
- CapabilityInstData capabilityInstance = buildCapabilityInstanceData(resourceInstanceId, overrideCapabilityDefinitionWrapper.getInnerElement());
- createCapabilityRes = createCapabilityInstanceOnGraph(riVertex, resourceInstanceId, overrideCapabilityDataWrapper.getInnerElement(), capabilityInstance);
- if (createCapabilityRes.isRight()) {
- errorWrapper.setInnerElement(createCapabilityRes.right().value());
- log.debug("Failed to create capability instance of capability {} of resource instance {}, status is {} ", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- }
- log.debug("After creating capability instance of capability {} on graph, status is {}", capabilityId, errorWrapper.getInnerElement());
- return createCapabilityRes;
- }
-
- private Either<CapabilityDefinition, TitanOperationStatus> getCapabiityDefinition(String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper, Wrapper<CapabilityData> overrideCapabilityDataWrapper,
- Either<ImmutablePair<CapabilityData, GraphEdge>, TitanOperationStatus> getCapabilityRes) {
- Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes;
- log.debug("Before getting capability definition {} for resource instance {}", capabilityId, resourceInstanceId);
- CapabilityData overrideCapabilityData = getCapabilityRes.left().value().getLeft();
- overrideCapabilityDataWrapper.setInnerElement(overrideCapabilityData);
- getCapabilityDefinitionRes = capabilityOperation.getCapabilityByCapabilityData(overrideCapabilityData);
- if (getCapabilityDefinitionRes.isRight()) {
- errorWrapper.setInnerElement(getCapabilityDefinitionRes.right().value());
- log.debug("Failed to retrieve capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- }
- log.debug("After getting capability definition for {} for resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- return getCapabilityDefinitionRes;
- }
-
- private Either<CapabilityDefinition, TitanOperationStatus> getCapabiityDefinitionByVertex(String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper, Wrapper<TitanVertex> overrideCapabilityDataWrapper,
- Either<ImmutablePair<TitanVertex, Edge>, TitanOperationStatus> getCapabilityRes) {
- Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes;
- log.trace("Before getting capability definition {} for resource instance {}", capabilityId, resourceInstanceId);
-
- TitanVertex overrideCapabilityData = getCapabilityRes.left().value().getLeft();
-
- overrideCapabilityDataWrapper.setInnerElement(overrideCapabilityData);
- getCapabilityDefinitionRes = capabilityOperation.getCapabilityByCapabilityData(overrideCapabilityData);
- if (getCapabilityDefinitionRes.isRight()) {
- errorWrapper.setInnerElement(getCapabilityDefinitionRes.right().value());
- log.debug("Failed to retrieve capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- }
- log.debug("After getting capability definition for {} for resource instance {} status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- return getCapabilityDefinitionRes;
- }
-
- private Either<ImmutablePair<CapabilityData, GraphEdge>, TitanOperationStatus> getCapabilitiesOfResourceInstance(String resourceInstanceId, String capabilityId, String capabilityName, Wrapper<TitanOperationStatus> errorWrapper) {
- Either<ImmutablePair<CapabilityData, GraphEdge>, TitanOperationStatus> getCapabilityRes;
- log.debug("Before getting capability {} for resource instance {}", capabilityId, resourceInstanceId);
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName);
- getCapabilityRes = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class, props);
- if (getCapabilityRes.isRight()) {
- errorWrapper.setInnerElement(getCapabilityRes.right().value());
- log.debug("Failed to get capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- }
- log.debug("After getting capability for {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- return getCapabilityRes;
- }
-
- private Either<ImmutablePair<TitanVertex, Edge>, TitanOperationStatus> getCapabilitiesOfResourceInstance(TitanVertex instanceVertex, String resourceInstanceId, String capabilityId, String capabilityName,
- Wrapper<TitanOperationStatus> errorWrapper) {
- Either<ImmutablePair<TitanVertex, Edge>, TitanOperationStatus> getCapabilityRes;
- log.trace("Before getting capability {} {} {}", capabilityId, " for resource instance ", resourceInstanceId);
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName);
- getCapabilityRes = titanGenericDao.getChildByEdgeCriteria(instanceVertex, GraphEdgeLabels.CALCULATED_CAPABILITY, props);
- if (getCapabilityRes.isRight()) {
- errorWrapper.setInnerElement(getCapabilityRes.right().value());
- log.debug("Failed to get capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- }
- log.trace("After getting capability for {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- return getCapabilityRes;
- }
-
- private void validateCapabilityInstanceExistence(String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper) {
- log.debug("Before validation of existence of capability instance of capability {} for resource instance {}", capabilityId, resourceInstanceId);
- boolean capabilityInstOfCapabilityAlreadyExists;
- Either<Boolean, TitanOperationStatus> validateCapabilityInstExistenceRes = validateCapabilityInstExistence(resourceInstanceId, capabilityId);
- if (validateCapabilityInstExistenceRes.isRight()) {
- errorWrapper.setInnerElement(validateCapabilityInstExistenceRes.right().value());
- log.debug("Failed to validate uniqueness of capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- } else {
- capabilityInstOfCapabilityAlreadyExists = validateCapabilityInstExistenceRes.left().value();
- if (capabilityInstOfCapabilityAlreadyExists) {
- errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST);
- log.debug("Failed to create capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- }
- }
- log.debug("After validation of existence of capability instance of capability {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- }
-
- private void validateCapabilityInstanceExistence(TitanVertex resourceInstanceVertex, String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper) {
- log.trace("Before validation of existence of capability instance of capability {} for resource instance {}", capabilityId, resourceInstanceId);
- boolean capabilityInstOfCapabilityAlreadyExists;
- Either<Boolean, TitanOperationStatus> validateCapabilityInstExistenceRes = validateCapabilityInstExistence(resourceInstanceId, capabilityId);
- if (validateCapabilityInstExistenceRes.isRight()) {
- errorWrapper.setInnerElement(validateCapabilityInstExistenceRes.right().value());
- log.debug("Failed to validate uniqueness of capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- } else {
- capabilityInstOfCapabilityAlreadyExists = validateCapabilityInstExistenceRes.left().value();
- if (capabilityInstOfCapabilityAlreadyExists) {
- errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST);
- log.debug("Failed to create capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- }
- }
- log.debug("After validation of existence of capability instance of capability {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement());
- }
-
- private Either<List<PropertyValueData>, TitanOperationStatus> addPropertyValuesToCapabilityInstance(CapabilityInstData createdCapabilityInstance, List<ComponentInstanceProperty> propertyValues, Map<String, PropertyDefinition> defaultProperties) {
- TitanOperationStatus error = null;
- List<PropertyValueData> createdPropertyValues = new ArrayList<>();
- for (ComponentInstanceProperty property : propertyValues) {
- log.debug("Before adding property value {} to capability instance {}", property.getName(), createdCapabilityInstance.getUniqueId());
- PropertyValueData propertyData = buildPropertyValueData(property.getName(), property.getType(), property.getValue(), createdCapabilityInstance.getUniqueId());
- Either<PropertyValueData, TitanOperationStatus> addPropertyValueRes = addPropertyValueToCapabilityInstance(createdCapabilityInstance, propertyData, defaultProperties.get(property.getName()));
- if (addPropertyValueRes.isRight()) {
- error = addPropertyValueRes.right().value();
- log.debug("Failed to add property to capability instance {} of resource instance, status is {}", createdCapabilityInstance.getUniqueId(), error);
- break;
- } else {
- createdPropertyValues.add(addPropertyValueRes.left().value());
- }
- log.debug("After adding property value {} to capability instance {}. status is {}", property.getName(), createdCapabilityInstance.getUniqueId(), error);
- }
- if (error == null) {
- return Either.left(createdPropertyValues);
- }
- return Either.right(error);
- }
-
- private TitanOperationStatus addPropertyValuesToCapabilityInstance(TitanVertex createdCapabilityInstancevertex, List<ComponentInstanceProperty> propertyValues, Map<String, PropertyDefinition> defaultProperties) {
- TitanOperationStatus error = null;
- String id = (String) titanGenericDao.getProperty(createdCapabilityInstancevertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- for (ComponentInstanceProperty property : propertyValues) {
- log.trace("Before adding property value {} to capability instance {}", property.getName(), id);
- PropertyValueData propertyData = buildPropertyValueData(property.getName(), property.getType(), property.getValue(), id);
- TitanOperationStatus addPropertyValueRes = addPropertyValueToCapabilityInstance(createdCapabilityInstancevertex, propertyData, defaultProperties.get(property.getName()), id);
- if (!addPropertyValueRes.equals(TitanOperationStatus.OK)) {
- error = addPropertyValueRes;
- log.debug("Failed to add property to capability instance {} of resource instance. status is {}", id, error);
- break;
- }
- log.debug("After adding property value {} to capability instance {}. status is {}", property.getName(), id, error);
- }
- if (error == null) {
- return TitanOperationStatus.OK;
- }
- return error;
- }
-
- private PropertyValueData buildPropertyValueData(String propertyName, String propertyType, String propertyValue, String capabilityInstanceId) {
- PropertyValueData propertyData = new PropertyValueData();
- String uniqueId = UniqueIdBuilder.buildPropertyValueUniqueId(capabilityInstanceId, propertyName);
- Long creationTime = System.currentTimeMillis();
- propertyData.setUniqueId(uniqueId);
- propertyData.setValue(propertyValue);
- propertyData.setType(propertyType);
- propertyData.setCreationTime(creationTime);
- propertyData.setModificationTime(creationTime);
- return propertyData;
- }
-
- private Either<PropertyValueData, TitanOperationStatus> addPropertyValueToCapabilityInstance(CapabilityInstData createdCapabilityInstance, PropertyValueData propertyValue, PropertyDefinition propertyDefinition) {
- TitanOperationStatus error = null;
- Map<String, Object> props = null;
- Either<GraphRelation, TitanOperationStatus> createRelationRes;
- PropertyValueData createdValue = null;
- log.debug("Before creating property value node {} on graph", propertyValue.getUniqueId());
- Either<PropertyValueData, TitanOperationStatus> createValueRes = titanGenericDao.createNode(propertyValue, PropertyValueData.class);
- if (createValueRes.isRight()) {
- error = createValueRes.right().value();
- log.debug("Failed to create property value for capability instance {} of resource instance. status is {}", createdCapabilityInstance.getUniqueId(), error);
- }
- log.debug("After creating property value node {} on graph. status is {}", propertyValue.getUniqueId(), error);
- if (error == null) {
- log.debug("Before creating relation from property value node {} to capability instance {}", propertyValue.getUniqueId(), createdCapabilityInstance.getUniqueId());
- createdValue = createValueRes.left().value();
- props = new HashMap<>();
- props.put(GraphPropertiesDictionary.PROPERTY_NAME.name(), propertyDefinition.getName());
- props.put(GraphPropertiesDictionary.PROPERTY_ID.name(), propertyDefinition.getUniqueId());
- createRelationRes = titanGenericDao.createRelation(createdCapabilityInstance, createdValue, GraphEdgeLabels.PROPERTY_VALUE, props);
- if (createRelationRes.isRight()) {
- error = createRelationRes.right().value();
- log.debug("Failed to create relation from capability instance {} to property value {}. status is {}", createdCapabilityInstance.getUniqueId(), createdValue.getUniqueId(), error);
- }
- log.debug("After creating relation from property value node {} to capability instance {}. status is {}", propertyValue.getUniqueId(), createdCapabilityInstance.getUniqueId(), error);
- }
- if (error == null) {
- log.debug("Before creating relation from property value node {} to property {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId());
- createRelationRes = titanGenericDao.createRelation(propertyValue, new PropertyData(propertyDefinition, null), GraphEdgeLabels.PROPERTY_IMPL, props);
- if (createRelationRes.isRight()) {
- error = createRelationRes.right().value();
- log.debug("Failed to create relation from property value {} to property {}. status is {}", createdValue.getUniqueId(), propertyDefinition.getUniqueId(), error);
- }
- log.debug("After creating relation from property value node {} to property {}. status is {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId(), error);
- }
- if (error == null) {
- return Either.left(createdValue);
- }
- return Either.right(error);
- }
-
- private TitanOperationStatus addPropertyValueToCapabilityInstance(TitanVertex createdCapabilityInstanceVertex, PropertyValueData propertyValue, PropertyDefinition propertyDefinition, String id) {
- TitanOperationStatus error = null;
- Map<String, Object> props = null;
- TitanOperationStatus createRelationRes;
- log.trace("Before creating property value node {} on graph.", propertyValue.getUniqueId());
- Either<TitanVertex, TitanOperationStatus> createValueRes = titanGenericDao.createNode(propertyValue);
- if (createValueRes.isRight()) {
- error = createValueRes.right().value();
- log.debug("Failed to create property value for capability instance {} of resource instance. status is {}", id, error);
- }
- log.trace("After creating property value node {} on graph status is {}", propertyValue.getUniqueId(), error);
- TitanVertex createdPropVertex = null;
- String createdId = null;
- if (error == null) {
- log.trace("Before creating relation from property value node {} to capability instance {} ", propertyValue.getUniqueId() , id);
- props = new HashMap<>();
- props.put(GraphPropertiesDictionary.PROPERTY_NAME.name(), propertyDefinition.getName());
- props.put(GraphPropertiesDictionary.PROPERTY_ID.name(), propertyDefinition.getUniqueId());
- createdPropVertex = createValueRes.left().value();
- createRelationRes = titanGenericDao.createEdge(createdCapabilityInstanceVertex, createdPropVertex, GraphEdgeLabels.PROPERTY_VALUE, props);
- if (!createRelationRes.equals(TitanOperationStatus.OK)) {
- error = createRelationRes;
- createdId = (String) titanGenericDao.getProperty(createdPropVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- log.debug("Failed to create relation from capability instance {} to property value {}. status is {}", id, createdId, error);
- }
- log.trace("After creating relation from property value node {} to capability instance {}. status is {}", propertyValue.getUniqueId(), id, error);
- }
- if (error == null) {
- log.trace("Before creating relation from property value node {} to property {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId());
- createRelationRes = titanGenericDao.createEdge(createdPropVertex, new PropertyData(propertyDefinition, null), GraphEdgeLabels.PROPERTY_IMPL, props);
- if (!createRelationRes.equals(TitanOperationStatus.OK)) {
- error = createRelationRes;
- log.debug("Failed to create relation from property value {} to property {}. status is {}", createdId, propertyDefinition.getUniqueId(), error);
- }
- log.debug("After creating relation from property value node {} to property {}. status is {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId(), error);
- }
- if (error == null) {
- return TitanOperationStatus.OK;
- }
- return error;
- }
-
- private Either<Boolean, TitanOperationStatus> validateCapabilityInstanceProperties(Map<String, PropertyDefinition> defaultProperties, List<ComponentInstanceProperty> propertyValues) {
- Either<Boolean, TitanOperationStatus> result = Either.left(true);
- for (ComponentInstanceProperty property : propertyValues) {
- result = validateUpdateCapabilityInstancePropertyValue(property, defaultProperties);
- if (result.isRight()) {
- break;
- }
- }
- return result;
- }
-
- private Either<Boolean, TitanOperationStatus> validateUpdateCapabilityInstancePropertyValue(ComponentInstanceProperty property, Map<String, PropertyDefinition> defaultProperties) {
- PropertyDefinition defaultProperty;
- String propertyName = property.getName();
- Either<Boolean, TitanOperationStatus> result = null;
- if (defaultProperties.containsKey(propertyName)) {
- defaultProperty = defaultProperties.get(propertyName);
- String propertyType = property.getType() == null || property.getType().isEmpty() ? defaultProperty.getType() : property.getType();
-
- String innerType = null;
- if (property.getSchema() != null && property.getSchema().getProperty() != null)
- innerType = property.getSchema().getProperty().getType();
- if (innerType == null && defaultProperty.getSchema() != null && defaultProperty.getSchema().getProperty() != null)
- innerType = defaultProperty.getSchema().getProperty().getType();
-
- if (defaultProperty.getType().equals(propertyType)) {
- String propertyValue = property.getValue();
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- log.debug("Failed to update property value. status is {}", status);
- result = Either.right(status);
- }
- if (result == null) {
- Either<Object, Boolean> updatedPropertyValueRes = propertyOperation.validateAndUpdatePropertyValue(propertyType, propertyValue, innerType, allDataTypes.left().value());
- if (updatedPropertyValueRes.isLeft()) {
- if (updatedPropertyValueRes.left().value() != null)
- property.setDefaultValue(updatedPropertyValueRes.left().value().toString());
- result = Either.left(true);
- } else {
- result = Either.right(TitanOperationStatus.INVALID_PROPERTY);
- }
- }
- log.debug("The property with name {} has invalid type {} or invalid value {}.", propertyName, propertyType, propertyValue);
-
- } else {
- result = Either.right(TitanOperationStatus.PROPERTY_NAME_ALREADY_EXISTS);
- log.debug("The property with name {} and different type already exists.", propertyName);
- }
- } else {
- result = Either.right(TitanOperationStatus.NOT_FOUND);
- log.debug("Failed to find property with name {}.", propertyName);
- }
- return result;
- }
-
- /**
- * validate capability instance uniqueness
- *
- * @param resourceInstanceId
- * @param capabilityId
- * @return
- */
- @Override
- public Either<Boolean, TitanOperationStatus> validateCapabilityInstExistence(String resourceInstanceId, String capabilityId) {
- Either<Boolean, TitanOperationStatus> result = null;
- TitanOperationStatus error;
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capabilityId);
- Either<Edge, TitanOperationStatus> getCapabilityInstanceEdgeRes = titanGenericDao.getOutgoingEdgeByCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, GraphEdgeLabels.CAPABILITY_INST, props);
- if (getCapabilityInstanceEdgeRes.isRight()) {
- error = getCapabilityInstanceEdgeRes.right().value();
- if (error.equals(TitanOperationStatus.NOT_FOUND)) {
- result = Either.left(false);
- } else {
- log.debug("Failed to get outgoing edge for resource instance {}. status is {}.", resourceInstanceId, error);
- result = Either.right(error);
- }
- }
- if (result == null) {
- result = Either.left(true);
- }
- return result;
- }
-
- @Override
- public Either<Boolean, TitanOperationStatus> validateCapabilityInstExistence(TitanVertex instanceVertex, String resourceInstanceId, String capabilityId) {
- Either<Boolean, TitanOperationStatus> result = null;
- TitanOperationStatus error;
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capabilityId);
- Either<Edge, TitanOperationStatus> getCapabilityInstanceEdgeRes = titanGenericDao.getOutgoingEdgeByCriteria(instanceVertex, GraphEdgeLabels.CAPABILITY_INST, props);
- if (getCapabilityInstanceEdgeRes.isRight()) {
- error = getCapabilityInstanceEdgeRes.right().value();
- if (error.equals(TitanOperationStatus.NOT_FOUND)) {
- result = Either.left(false);
- } else {
- log.debug("Failed to get outgoing edge for resource instance {} status is {}", resourceInstanceId, error);
- result = Either.right(error);
- }
- }
- if (result == null) {
- result = Either.left(true);
- }
- return result;
- }
-
- private Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceOnGraph(String resourceInstanceId, CapabilityData overrideCapabilityData, CapabilityInstData capabilityInstance) {
- log.debug("Before creation of capability instance of capability {} for resource instance {}", overrideCapabilityData.getUniqueId(), resourceInstanceId);
-
- Either<GraphRelation, TitanOperationStatus> createRelationRes;
- CapabilityInstData createdCapabilityInstance = null;
- String capabilityInstanceId = null;
- TitanOperationStatus error = null;
- Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceRes = titanGenericDao.createNode(capabilityInstance, CapabilityInstData.class);
- if (createCapabilityInstanceRes.isRight()) {
- error = createCapabilityInstanceRes.right().value();
- log.debug("Failed to create capability instance of capability {} for resource instance {}. status is {}.", overrideCapabilityData.getUniqueId(), resourceInstanceId, error);
- }
- log.debug("After creation of capability instance of capability {} for resource instance {}. status is {}.", overrideCapabilityData.getUniqueId(), resourceInstanceId, error);
- if (error == null) {
- createdCapabilityInstance = createCapabilityInstanceRes.left().value();
- capabilityInstanceId = createdCapabilityInstance.getUniqueId();
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), overrideCapabilityData.getUniqueId());
- UniqueIdData resourceInstanceIdData = new UniqueIdData(NodeTypeEnum.ResourceInstance, resourceInstanceId);
- log.debug("Before associating resource instance {} to capability instance.", resourceInstanceId);
- createRelationRes = titanGenericDao.createRelation(resourceInstanceIdData, capabilityInstance, GraphEdgeLabels.CAPABILITY_INST, props);
- if (createRelationRes.isRight()) {
- error = createRelationRes.right().value();
- log.debug("Failed to assotiate resource instance {} to capability instance {}. status is {}", resourceInstanceId, capabilityInstanceId, error);
- }
- log.debug("After associating resource instance {} to capability instance {}. status is {}", resourceInstanceId, capabilityInstanceId, error);
- }
- if (error == null) {
- log.debug("Before associating capability instance {} to capability {}.", capabilityInstanceId, overrideCapabilityData.getUniqueId());
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), overrideCapabilityData.getUniqueId());
- createRelationRes = titanGenericDao.createRelation(createdCapabilityInstance, overrideCapabilityData, GraphEdgeLabels.INSTANCE_OF, props);
- if (createRelationRes.isRight()) {
- error = createRelationRes.right().value();
- log.debug("Failed to associate capability instance {} to capability {}. status is {}", capabilityInstanceId, overrideCapabilityData.getUniqueId(), error);
- }
- log.debug("After associating capability instance {} to capability {}. status is {}.", capabilityInstanceId, overrideCapabilityData.getUniqueId(), error);
- }
- if (error == null) {
- return createCapabilityInstanceRes;
- }
- return Either.right(error);
- }
-
- private Either<TitanVertex, TitanOperationStatus> createCapabilityInstanceOnGraph(TitanVertex riVertex, String resourceInstanceId, TitanVertex overrideCapabilityDataVertex, CapabilityInstData capabilityInstance) {
- String overrideCapabilityDataId = (String) titanGenericDao.getProperty(overrideCapabilityDataVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- log.trace("Before creation of capability instance of capability {} for resource instance {}", overrideCapabilityDataVertex, resourceInstanceId);
-
- TitanOperationStatus createRelationRes;
- TitanVertex createdCapabilityInstance = null;
- String capabilityInstanceId = null;
- TitanOperationStatus error = null;
- Either<TitanVertex, TitanOperationStatus> createCapabilityInstanceRes = titanGenericDao.createNode(capabilityInstance);
- if (createCapabilityInstanceRes.isRight()) {
- error = createCapabilityInstanceRes.right().value();
- log.debug("Failed to create capability instance of capability {} for resource instance {} status is {}", overrideCapabilityDataId, resourceInstanceId, error);
- }
- log.trace("After creation of capability instance of capability {} for resource instance {} status is {}", overrideCapabilityDataId, resourceInstanceId, error);
- if (error == null) {
- createdCapabilityInstance = createCapabilityInstanceRes.left().value();
- capabilityInstanceId = (String) titanGenericDao.getProperty(createdCapabilityInstance, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), overrideCapabilityDataId);
- log.debug("Before associating resource instance {} to capability instance.", resourceInstanceId);
-
- createRelationRes = titanGenericDao.createEdge(riVertex, capabilityInstance, GraphEdgeLabels.CAPABILITY_INST, props);
- if (!createRelationRes.equals(TitanOperationStatus.OK)) {
- error = createRelationRes;
- log.debug("Failed to assotiate resource instance {} to capability instance {} status is {}", resourceInstanceId, capabilityInstanceId, error);
- }
- if (log.isTraceEnabled()) {
- log.trace("After associating resource instance {} to capability instance {}. status is {}", resourceInstanceId, capabilityInstanceId, error);
- }
- }
- if (error == null) {
- log.trace("Before associating capability instance {} to capability {}", capabilityInstanceId, overrideCapabilityDataId);
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), overrideCapabilityDataId);
- createRelationRes = titanGenericDao.createEdge(createdCapabilityInstance, overrideCapabilityDataVertex, GraphEdgeLabels.INSTANCE_OF, props);
- if (!createRelationRes.equals(TitanOperationStatus.OK)) {
- error = createRelationRes;
- log.debug("Failed to associate capability instance {} to capability {} status is {}", capabilityInstanceId, overrideCapabilityDataId, error);
- }
- log.debug("After associating capability instance {} to capability {}. status is {}", capabilityInstanceId, overrideCapabilityDataId, error);
- }
- if (error == null) {
- return createCapabilityInstanceRes;
- }
- return Either.right(error);
- }
-
- private CapabilityInstData buildCapabilityInstanceData(String resourceInstanceId, CapabilityDefinition capability) {
- CapabilityInstData capabilityInstance = new CapabilityInstData();
- Long creationTime = System.currentTimeMillis();
- String uniqueId = UniqueIdBuilder.buildCapabilityInstanceUid(resourceInstanceId, capability.getName());
-
- capabilityInstance.setCreationTime(creationTime);
- capabilityInstance.setModificationTime(creationTime);
- capabilityInstance.setUniqueId(uniqueId);
-
- return capabilityInstance;
- }
-
- /**
- * delete capability instance from resource instance
- *
- * @param resourceInstanceId
- * @param capabilityInstanceId
- * @return
- */
- @Override
- public Either<CapabilityInstData, TitanOperationStatus> deleteCapabilityInstanceFromResourceInstance(String resourceInstanceId, String capabilityInstanceId) {
- log.debug("Before deleting of capability instance {} from resource instance {}.", capabilityInstanceId, resourceInstanceId);
-
- Either<CapabilityInstData, TitanOperationStatus> deleteCapabilityInstRes = null;
- TitanOperationStatus error = null;
- Either<Boolean, TitanOperationStatus> deleteProperyValuesRes = deleteAllPropertyValuesOfCapabilityInstance(resourceInstanceId, capabilityInstanceId);
- if (deleteProperyValuesRes.isRight()) {
- error = deleteProperyValuesRes.right().value();
- log.debug("Failed to delete property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
- }
- if (error == null) {
- deleteCapabilityInstRes = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstanceId, CapabilityInstData.class);
- if (deleteCapabilityInstRes.isRight()) {
- error = deleteCapabilityInstRes.right().value();
- log.debug("Failed to delete capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
- }
- }
- log.debug("After deleting of capability instance {} from resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
- if (error == null) {
- return Either.left(deleteCapabilityInstRes.left().value());
- }
- return Either.right(error);
- }
-
- private Either<Boolean, TitanOperationStatus> deleteAllPropertyValuesOfCapabilityInstance(String resourceInstanceId, String capabilityInstanceId) {
- log.debug("Before deleting all property values of capability instance {} from resource instance {}", capabilityInstanceId, resourceInstanceId);
- TitanOperationStatus error = null;
- List<ImmutablePair<PropertyValueData, GraphEdge>> deletePropertiesPairs;
- Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> getPropertyValuesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstanceId,
- GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class);
- if (getPropertyValuesRes.isRight()) {
- error = getPropertyValuesRes.right().value();
- log.debug("Failed to retrieve property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
- }
- if (error == null) {
- deletePropertiesPairs = getPropertyValuesRes.left().value();
- for (ImmutablePair<PropertyValueData, GraphEdge> propertyPair : deletePropertiesPairs) {
- Either<PropertyValueData, TitanOperationStatus> deletePropertyRes = titanGenericDao.deleteNode(propertyPair.getLeft(), PropertyValueData.class);
- if (deletePropertyRes.isRight()) {
- error = deletePropertyRes.right().value();
- log.debug("Failed to delete property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
- break;
- }
- }
- }
- log.debug("After deleting all property values of capability instance from resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
- if (error == null) {
- return Either.left(true);
- }
- return Either.right(error);
- }
-
- /**
- * get all capability instances for resource instance returns all Capability Instances related to Resource Instance as List<CapabilityInstData> or TitanOperationStatus if error occurs or if Resource Instance have no any related Capability
- * Instance
- *
- * @param resourceInstanceId
- * @return Either<List<CapabilityInstData>, TitanOperationStatus>
- */
- @Override
- public Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesOfResourceInstance(String resourceInstanceId) {
- log.debug("Before deleting all capability instances of resource instance {}", resourceInstanceId);
- TitanOperationStatus error = null;
- Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId,
- GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class);
- if (getCapabilityInstancesRes.isRight()) {
- error = getCapabilityInstancesRes.right().value();
- log.debug("Failed to retrieve capability Instances of resource instance {}. status is {}", resourceInstanceId, error);
- }
- log.debug("After deleting all capability instances of resource instance {}. status is {}", resourceInstanceId, error);
- if (error == null) {
- return getCapabilityInstancesRes;
- }
- return Either.right(error);
- }
-
- /**
- * get capability instance of capability for resource instance
- *
- * @param resourceInstanceId
- * @param capabilityId
- * @return
- */
- @Override
- public Either<CapabilityInstData, TitanOperationStatus> getCapabilityInstanceOfCapabilityOfResourceInstance(String resourceInstanceId, String capabilityId) {
- TitanOperationStatus error = null;
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capabilityId);
- Either<ImmutablePair<CapabilityInstData, GraphEdge>, TitanOperationStatus> getCapabilityInstanceRes = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId,
- GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class, props);
- if (getCapabilityInstanceRes.isRight()) {
- error = getCapabilityInstanceRes.right().value();
- log.debug("Failed to retrieve capability Instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error);
- }
- if (error == null) {
- return Either.left(getCapabilityInstanceRes.left().value().getLeft());
- }
- return Either.right(error);
- }
-
- /**
- * update capability property values
- *
- * @param resourceInstanceId
- * @param propertyValues
- * @param capabilityId
- * @return
- */
- @Override
- public Either<List<PropertyValueData>, TitanOperationStatus> updateCapabilityPropertyValues(String resourceInstanceId, String capabilityId, List<ComponentInstanceProperty> propertyValues) {
- log.debug("Before updating property values of capability {} of resource instance {}.", capabilityId, resourceInstanceId);
- TitanOperationStatus error = null;
- Map<String, Object> props = new HashMap<>();
- CapabilityInstData capabilityInstance = null;
- String capabilityInstanceId = null;
- Either<Boolean, TitanOperationStatus> deleteProperyValuesRes;
-
- CapabilityData overrideCapabilityData;
- CapabilityDefinition overrideCapabilityDefinition;
- Map<String, PropertyDefinition> defaultProperties = null;
- Either<ImmutablePair<CapabilityData, GraphEdge>, TitanOperationStatus> getCapabilityDataRes = null;
- Either<List<PropertyValueData>, TitanOperationStatus> addPropertyValuesRes = null;
- Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes = null;
-
- log.debug("Before getting all capability instances of resource instance {}.", resourceInstanceId);
- props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capabilityId);
- Either<ImmutablePair<CapabilityInstData, GraphEdge>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId,
- GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class, props);
- if (getCapabilityInstancesRes.isRight()) {
- error = getCapabilityInstancesRes.right().value();
- log.debug("Failed to retrieve capability Instances of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error);
- }
- log.debug("After getting all capability instances of resource instance {}. status is {}.", resourceInstanceId, error);
- if (error == null) {
- log.debug("Before deleting all capability instances of resource instance {}.", resourceInstanceId);
- capabilityInstance = getCapabilityInstancesRes.left().value().getLeft();
- capabilityInstanceId = capabilityInstance.getUniqueId();
- deleteProperyValuesRes = deleteAllPropertyValuesOfCapabilityInstance(resourceInstanceId, capabilityInstanceId);
- if (deleteProperyValuesRes.isRight()) {
- error = deleteProperyValuesRes.right().value();
- log.debug("Failed to delete property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
- }
- log.debug("After deleting all capability instances of resource instance {}. status is {}", resourceInstanceId, error);
- }
- if (error == null) {
- log.debug("Before getting capability {} of resource instance {}", capabilityId, resourceInstanceId);
- getCapabilityDataRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class);
- if (getCapabilityDataRes.isRight()) {
- error = getCapabilityDataRes.right().value();
- log.debug("Failed to get capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error);
- }
- log.debug("After getting capability {} of resource instance {}. status is {}.", capabilityId, resourceInstanceId, error);
- }
- if (error == null) {
- log.debug("Before getting capability definition for capability {} of resource instance {}.", capabilityId, resourceInstanceId);
- overrideCapabilityData = getCapabilityDataRes.left().value().getLeft();
- getCapabilityDefinitionRes = capabilityOperation.getCapabilityByCapabilityData(overrideCapabilityData);
- if (getCapabilityDefinitionRes.isRight()) {
- error = getCapabilityDefinitionRes.right().value();
- log.debug("Failed to retrieve capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error);
- }
- log.debug("After getting capability definition for capability {} of resource instance {}. status is {}.", capabilityId, resourceInstanceId, error);
- }
- if (error == null) {
- log.debug("Before validating capability properties of capability instance {} of resource instance {}.", capabilityInstanceId, resourceInstanceId);
- overrideCapabilityDefinition = getCapabilityDefinitionRes.left().value();
- if (overrideCapabilityDefinition.getProperties() != null) {
- defaultProperties = overrideCapabilityDefinition.getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity()));
- }
- Either<Boolean, TitanOperationStatus> result = validateCapabilityInstanceProperties(defaultProperties, propertyValues);
- if (result.isRight()) {
- error = result.right().value();
- log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}", capabilityInstance.getUniqueId(), resourceInstanceId, error);
- }
- log.debug("After validating capability properties of capability instance {} of resource instance {}. status is {}.", capabilityInstanceId, resourceInstanceId, error);
- }
- if (error == null) {
- log.debug("Before adding property values to capability instance {} of resource instance {}.", capabilityInstanceId, resourceInstanceId);
- addPropertyValuesRes = addPropertyValuesToCapabilityInstance(capabilityInstance, propertyValues, defaultProperties);
- if (addPropertyValuesRes.isRight()) {
- error = addPropertyValuesRes.right().value();
- log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}", capabilityInstance.getUniqueId(), resourceInstanceId, error);
- }
- log.debug("Before adding property values to capability instance {} of resource instance {}.", capabilityInstanceId, resourceInstanceId);
- }
- log.debug("After updating property values of capability {} of resource instance {}. status is {}.", capabilityId, resourceInstanceId, error);
- if (error == null) {
- return addPropertyValuesRes;
- }
- return Either.right(error);
- }
-
- /**
- * clone and associate capability instance with property values
- *
- * @param createdComponentInstance
- * @param capability
- * @param capabilityInstPair
- * @return
- */
- @Override
- public Either<ImmutablePair<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> cloneAssociateCapabilityInstanceWithPropertyValues(ComponentInstanceData createdComponentInstance, CapabilityDefinition capability,
- ImmutablePair<CapabilityInstData, GraphEdge> capabilityInstPair) {
-
- TitanOperationStatus error = null;
- String componentInstanceId = createdComponentInstance.getUniqueId();
- String capabilityInstanceId = capabilityInstPair.getLeft().getUniqueId();
-
- log.debug("Before cloning capability instance with property values of capability instance {} of resource instance {}.", capabilityInstanceId, componentInstanceId);
- List<ImmutablePair<PropertyValueData, GraphEdge>> propertyValuePairs;
- List<PropertyValueData> newPropertyValues = new ArrayList<>();
- CapabilityInstData cloneCapabilityInstance = null;
- Either<CapabilityInstData, TitanOperationStatus> cloneCapabilityInstanceNodeRes = null;
-
- log.debug("Before getting all property values of component instance {} of resource instance {}.", capabilityInstanceId, componentInstanceId);
- Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> getPropertyValuesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstPair.getLeft().getUniqueId(),
- GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class);
- if (getPropertyValuesRes.isRight()) {
- error = getPropertyValuesRes.right().value();
- log.debug("Failed to retrieve property values of capability instance {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), componentInstanceId, error);
- }
- log.debug("After getting all property values of component instance {} of resource instance {}. status is {}.", capabilityInstanceId, componentInstanceId, error);
- if (error == null) {
- CapabilityInstData cloneCapabilityInst = buildCapabilityInstanceData(componentInstanceId, capability);
- log.debug("Before creating capability instance node {} on graph.", cloneCapabilityInst.getUniqueId());
- cloneCapabilityInstanceNodeRes = titanGenericDao.createNode(cloneCapabilityInst, CapabilityInstData.class);
- if (cloneCapabilityInstanceNodeRes.isRight()) {
- error = cloneCapabilityInstanceNodeRes.right().value();
- log.debug("Failed to create capability instance of capability {} of component instance {}. status is {}", capability.getUniqueId(), componentInstanceId, error);
- }
- log.debug("After creating capability instance node {} on graph. status is {}.", cloneCapabilityInst.getUniqueId(), error);
- }
-
- if (error == null) {
- log.debug("Before creating relation from capability instance {} to capability {} on graph.", cloneCapabilityInstanceNodeRes.left().value().getUniqueId(), capability.getUniqueId());
- cloneCapabilityInstance = cloneCapabilityInstanceNodeRes.left().value();
- CapabilityData capabilityData = buildCapabilityData(capability);
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capabilityData.getUniqueId());
- Either<GraphRelation, TitanOperationStatus> createRelationRes = titanGenericDao.createRelation(cloneCapabilityInstance, capabilityData, GraphEdgeLabels.INSTANCE_OF, props);
- if (createRelationRes.isRight()) {
- error = createRelationRes.right().value();
- log.debug("Failed to associate capability instance {} to capability {}. status is {}", cloneCapabilityInstance.getUniqueId(), capability.getUniqueId(), error);
- }
- log.debug("After creating relation from capability instance {} to capability {} on graph. status is.", cloneCapabilityInstanceNodeRes.left().value().getUniqueId(), capability.getUniqueId(), error);
- }
-
- if (error == null) {
- log.debug("Before cloning property values of component instance {}.", capabilityInstanceId);
- propertyValuePairs = getPropertyValuesRes.left().value();
- for (ImmutablePair<PropertyValueData, GraphEdge> propertyValuePair : propertyValuePairs) {
- Either<PropertyValueData, TitanOperationStatus> clonePropertyValueRes = cloneAssociatePropertyValue(cloneCapabilityInstance, propertyValuePair);
- if (clonePropertyValueRes.isRight()) {
- error = clonePropertyValueRes.right().value();
- log.debug("Failed to clone property value {} of capability {} of component instance {}. status is {}", propertyValuePair.getLeft().getUniqueId(), capability.getUniqueId(), componentInstanceId, error);
- break;
- } else {
- newPropertyValues.add(clonePropertyValueRes.left().value());
- }
- }
- log.debug("After cloning property values of component instance {}. status is {}.", capabilityInstanceId, error);
- }
- log.debug("After cloning capability instance with property values of capability instance {} of resource instance {}. status is {}.", capabilityInstanceId, componentInstanceId, error);
- if (error == null) {
- return Either.left(new ImmutablePair<CapabilityInstData, List<PropertyValueData>>(cloneCapabilityInstance, newPropertyValues));
- }
- return Either.right(error);
- }
-
- public Either<TitanVertex, TitanOperationStatus> cloneAssociateCapabilityInstanceWithPropertyValues(TitanVertex componentInstanceVertex, CapabilityDefinition capability, ImmutablePair<CapabilityInstData, GraphEdge> capabilityInstPair) {
-
- TitanOperationStatus error = null;
- String componentInstanceId = (String) titanGenericDao.getProperty(componentInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- String capabilityInstanceId = capabilityInstPair.getLeft().getUniqueId();
-
- if (log.isTraceEnabled()) {
- log.trace("Before cloning capability instance with property values of capability instance {} of resource instance {}", capabilityInstanceId, componentInstanceId);
- }
- List<ImmutablePair<TitanVertex, Edge>> propertyValuePairs;
- Either<TitanVertex, TitanOperationStatus> cloneCapabilityInstanceNodeRes = null;
-
- if (log.isTraceEnabled()) {
- log.trace("Before getting all property values of component instance {} of resource instance {}", capabilityInstanceId, componentInstanceId);
- }
- Either<List<ImmutablePair<TitanVertex, Edge>>, TitanOperationStatus> getPropertyValuesRes = titanGenericDao.getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstPair.getLeft().getUniqueId(),
- GraphEdgeLabels.PROPERTY_VALUE);
- if (getPropertyValuesRes.isRight()) {
- error = getPropertyValuesRes.right().value();
- log.debug("Failed to retrieve property values of capability instance {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), componentInstanceId, error);
- }
- if (log.isTraceEnabled()) {
- log.trace("After getting all property values of component instance {} of resource instance {}. status is {}", capabilityInstanceId, componentInstanceId, error);
- }
- if (error == null) {
- CapabilityInstData cloneCapabilityInst = buildCapabilityInstanceData(componentInstanceId, capability);
- log.trace("Before creating capability instance node {} on graph", cloneCapabilityInst.getUniqueId());
- cloneCapabilityInstanceNodeRes = titanGenericDao.createNode(cloneCapabilityInst);
- if (cloneCapabilityInstanceNodeRes.isRight()) {
- error = cloneCapabilityInstanceNodeRes.right().value();
- log.debug("Failed to create capability instance of capability {} of component instance {}. status is {}", capability.getUniqueId(), componentInstanceId, error);
- }
- if (log.isTraceEnabled()) {
- log.trace("After creating capability instance node {} on graph. status is {}", cloneCapabilityInst.getUniqueId(), error);
- }
- }
- CapabilityData capabilityData;
- TitanVertex cloneCapabilityInstance = null;
- if (error == null) {
- if (log.isTraceEnabled()) {
- log.trace("Before creating relation from capability instance {} to capability {} on graph", capability.getUniqueId(), capability.getUniqueId());
- }
- capabilityData = buildCapabilityData(capability);
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capabilityData.getUniqueId());
- cloneCapabilityInstance = cloneCapabilityInstanceNodeRes.left().value();
- TitanOperationStatus createRelationRes = titanGenericDao.createEdge(cloneCapabilityInstance, capabilityData, GraphEdgeLabels.INSTANCE_OF, props);
- if (!createRelationRes.equals(TitanOperationStatus.OK)) {
- error = createRelationRes;
- log.debug("Failed to associate capability instance {} to capability {}. status is {}", capabilityData.getUniqueId(), capability.getUniqueId(), createRelationRes);
- }
- log.trace("After creating relation from capability instance {} to capability {} on graph. status is {}", capabilityData.getUniqueId(), capability.getUniqueId(), error);
- }
-
- if (error == null) {
- log.trace("Before cloning property values of component instance {} ", capabilityInstanceId);
- propertyValuePairs = getPropertyValuesRes.left().value();
- for (ImmutablePair<TitanVertex, Edge> propertyValuePair : propertyValuePairs) {
- TitanOperationStatus clonePropertyValueRes = cloneAssociatePropertyValue(cloneCapabilityInstance, propertyValuePair);
- if (!clonePropertyValueRes.equals(TitanOperationStatus.OK)) {
- error = clonePropertyValueRes;
- log.debug("Failed to clone property value of capability {} of component instance {}. status is {}", capability.getUniqueId(), componentInstanceId, error);
- break;
- }
- }
- log.debug("After cloning property values of component instance {}. status is {}", capabilityInstanceId, error);
- }
- log.debug("After cloning capability instance with property values of capability instance {} of resource instance {}. status is {}.", capabilityInstanceId, componentInstanceId, error);
- if (error == null) {
- return Either.left(cloneCapabilityInstance);
- }
- return Either.right(error);
- }
-
- private CapabilityData buildCapabilityData(CapabilityDefinition capability) {
- CapabilityData capabilityData = new CapabilityData();
- capabilityData.setUniqueId(capability.getUniqueId());
- capabilityData.setDescription(capability.getDescription());
- capabilityData.setType(capability.getType());
- capabilityData.setMaxOccurrences(capability.getMaxOccurrences());
- capabilityData.setMinOccurrences(capability.getMinOccurrences());
- List<String> validSourceTypes = capability.getValidSourceTypes();
- if (validSourceTypes != null) {
- capabilityData.setValidSourceTypes(validSourceTypes);
- }
- return capabilityData;
- }
-
- private Either<PropertyValueData, TitanOperationStatus> cloneAssociatePropertyValue(CapabilityInstData cloneCapabilityInstance, ImmutablePair<PropertyValueData, GraphEdge> propertyValuePair) {
- TitanOperationStatus error = null;
- String propertyValueID = propertyValuePair.getLeft().getUniqueId();
- String capabilityInstanceId = cloneCapabilityInstance.getUniqueId();
- log.debug("Before cloning property values {} of component instance {}.", propertyValueID, capabilityInstanceId);
-
- Map<String, Object> props = propertyValuePair.getRight().getProperties();
- PropertyData propertyData = new PropertyData();
- String propertyId = (String) props.get(GraphPropertiesDictionary.PROPERTY_ID.name());
- propertyData.getPropertyDataDefinition().setUniqueId(propertyId);
-
- PropertyValueData propertyValue = buildPropertyValueData((String) props.get(GraphPropertiesDictionary.PROPERTY_NAME.name()), propertyValuePair.getLeft().getType(), propertyValuePair.getLeft().getValue(), capabilityInstanceId);
- PropertyValueData createdValue = null;
- Either<GraphRelation, TitanOperationStatus> createRelationRes;
-
- log.debug("Before creating property values node {} on graph.", propertyValue.getUniqueId());
- Either<PropertyValueData, TitanOperationStatus> createValueRes = titanGenericDao.createNode(propertyValue, PropertyValueData.class);
- if (createValueRes.isRight()) {
- error = createValueRes.right().value();
- log.debug("Failed to create property value for capability instance {} of resource instance. status is {}.", cloneCapabilityInstance.getUniqueId(), error);
- }
- log.debug("After creating property values node {} on graph. status is {}.", propertyValue.getUniqueId(), error);
- if (error == null) {
- createdValue = createValueRes.left().value();
- log.debug("Before creating relation from capability instance {} to property value {}.", capabilityInstanceId, createdValue.getUniqueId());
- createRelationRes = titanGenericDao.createRelation(cloneCapabilityInstance, createdValue, GraphEdgeLabels.PROPERTY_VALUE, props);
- if (createRelationRes.isRight()) {
- error = createRelationRes.right().value();
- log.debug("Failed to create relation from capability instance {} to property value {}. status is {}.", cloneCapabilityInstance.getUniqueId(), createdValue.getUniqueId(), error);
- }
- log.debug("After creating relation from capability instance {} to property value {}. status is {}.", capabilityInstanceId, createdValue.getUniqueId(), error);
- }
- if (error == null) {
- log.debug("Before creating relation from property value {} to property {}.", createdValue, propertyData.getUniqueId());
- createRelationRes = titanGenericDao.createRelation(createdValue, propertyData, GraphEdgeLabels.PROPERTY_IMPL, props);
- if (createRelationRes.isRight()) {
- error = createRelationRes.right().value();
- log.debug("Failed to create relation from property value {} to property {}. status is {}.", createdValue.getUniqueId(), propertyId, error);
- }
- log.debug("Before creating relation from property value {} to property {}. status is {}.", createdValue, propertyData.getUniqueId(), error);
- }
- log.debug("After cloning property values {} of component instance {}. status is {}.", propertyValueID, capabilityInstanceId, error);
- if (error == null) {
- return Either.left(createdValue);
- }
- return Either.right(error);
- }
-
- private TitanOperationStatus cloneAssociatePropertyValue(TitanVertex capabilityInstanceVertex, ImmutablePair<TitanVertex, Edge> propertyValuePair) {
- TitanOperationStatus error = null;
- TitanVertex propertyVertex = propertyValuePair.getLeft();
- String propertyValueID = (String) titanGenericDao.getProperty(propertyVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- String capabilityInstanceId = (String) titanGenericDao.getProperty(capabilityInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- if (log.isTraceEnabled()) {
- log.trace("Before cloning property values {} of component instance {}", propertyValueID, capabilityInstanceId);
- }
-
- Map<String, Object> props = titanGenericDao.getProperties(propertyValuePair.getRight());
- PropertyData propertyData = new PropertyData();
- String propertyId = (String) props.get(GraphPropertiesDictionary.PROPERTY_ID.name());
- propertyData.getPropertyDataDefinition().setUniqueId(propertyId);
-
- String propertyType = (String) titanGenericDao.getProperty(propertyVertex, GraphPropertiesDictionary.TYPE.getProperty());
- String propertyValueStr = (String) titanGenericDao.getProperty(propertyVertex, GraphPropertiesDictionary.VALUE.getProperty());
-
- PropertyValueData propertyValue = buildPropertyValueData((String) props.get(GraphPropertiesDictionary.PROPERTY_NAME.name()), propertyType, propertyValueStr, capabilityInstanceId);
- TitanVertex createdValue = null;
- TitanOperationStatus createRelationRes;
-
- log.trace("Before creating property values node {} on graph.", propertyValue.getUniqueId());
- Either<TitanVertex, TitanOperationStatus> createValueRes = titanGenericDao.createNode(propertyValue);
- String capabiltyInstId = (String) titanGenericDao.getProperty(capabilityInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- if (createValueRes.isRight()) {
- error = createValueRes.right().value();
- log.debug("Failed to create property value for capability instance {} of resource instance. status is {}", capabiltyInstId, error);
- }
- if (log.isTraceEnabled()) {
- log.trace("After creating property values node {} on graph. status is {} ", propertyValue.getUniqueId(), error);
- }
- if (error == null) {
- createdValue = createValueRes.left().value();
- log.trace("Before creating relation from capability instance {} to property value {}", capabilityInstanceId, propertyValue.getUniqueId());
- createRelationRes = titanGenericDao.createEdge(capabilityInstanceVertex, createdValue, GraphEdgeLabels.PROPERTY_VALUE, props);
- if (!createRelationRes.equals(TitanOperationStatus.OK)) {
- error = createRelationRes;
- log.debug("Failed to create relation from capability instance {} to property value {}. status is {}", capabiltyInstId, propertyValue.getUniqueId(), error);
- }
- if (log.isTraceEnabled()) {
- log.trace("After creating relation from capability instance {} to property value {}. status is {} ", capabilityInstanceId, propertyValue.getUniqueId(), error);
- }
- }
- if (error == null) {
- log.trace("Before creating relation from property value {} to property {} ", createdValue, propertyData.getUniqueId());
- createRelationRes = titanGenericDao.createEdge(createdValue, propertyData, GraphEdgeLabels.PROPERTY_IMPL, props);
- if (!createRelationRes.equals(TitanOperationStatus.OK)) {
- error = createRelationRes;
- log.debug("Failed to create relation from property value {} to property {}. status is {}", propertyValue.getUniqueId(), propertyId, error);
- }
- if (log.isTraceEnabled()) {
- log.trace("Before creating relation from property value {} to property {}. status is {}", createdValue, propertyData.getUniqueId(), error);
- }
- }
- log.trace("After cloning property values {} of component instance {}. status is {}", propertyValueID, capabilityInstanceId, error);
- if (error == null) {
- return TitanOperationStatus.OK;
- }
- return error;
- }
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java
index ad43c60b0f..a4be274781 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java
@@ -89,934 +89,8 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
this.titanGenericDao = titanGenericDao;
}
- @Override
- public Either<CapabilityDefinition, StorageOperationStatus> addCapability(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition, boolean inTransaction) {
-
- Either<CapabilityDefinition, StorageOperationStatus> result = null;
-
- try {
-
- Either<CapabilityData, TitanOperationStatus> addCapStatus = addCapabilityToResource(resourceId, capabilityName, capabilityDefinition);
-
- if (addCapStatus.isRight()) {
- log.debug("Failed to add capability {} [{}] to Graph", capabilityName, capabilityDefinition);
- BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add Capability", capabilityName, String.valueOf(addCapStatus.right().value()));
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addCapStatus.right().value()));
- return result;
- } else {
- CapabilityData capabilityData = addCapStatus.left().value();
-
- String capabilityUid = capabilityData.getUniqueId();
- Either<CapabilityDefinition, StorageOperationStatus> capabilityRes = getCapability(capabilityUid, true);
- log.debug("After fetching capability {} with uid {}. status is {}" ,capabilityName, capabilityUid,capabilityRes);
-
- if (capabilityRes.isRight()) {
- StorageOperationStatus status = capabilityRes.right().value();
- log.debug("Failed to fetch capability {} with uid {}. status is {}", capabilityName, capabilityUid, status);
- result = Either.right(status);
- return result;
- }
-
- CapabilityDefinition value = capabilityRes.left().value();
- log.debug("The returned CapabilityDefinition is {}", value);
- result = Either.left(value);
-
- return result;
- }
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public StorageOperationStatus addCapability(TitanVertex metadataVertex, String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition, boolean inTransaction) {
-
- StorageOperationStatus result = StorageOperationStatus.OK;
- try {
-
- TitanOperationStatus addCapStatus = addCapabilityToResource(metadataVertex, resourceId, capabilityName, capabilityDefinition);
-
- if (!addCapStatus.equals(TitanOperationStatus.OK)) {
- log.debug("Failed to add capability {} [{}] to Graph", capabilityName, capabilityDefinition);
- BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add Capability", capabilityName, String.valueOf(addCapStatus));
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(addCapStatus);
- }
- } finally {
- if (false == inTransaction) {
- if (result == null || !result.equals(TitanOperationStatus.OK)) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- return result;
- }
-
- private CapabilityDefinition convertCDataToCDefinition(CapabilityData capabilityData) {
-
- CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
- capabilityDefinition.setType(capabilityData.getType());
-
- return capabilityDefinition;
- }
-
- @Override
- public Either<CapabilityDefinition, StorageOperationStatus> getCapability(String uniqueId) {
-
- return getCapability(uniqueId, false);
- }
-
- public Either<Map<String, CapabilityDefinition>, StorageOperationStatus> getAllCapabilitiesOfResource(String resourceId, boolean recursively, boolean inTransaction) {
-
- Map<String, CapabilityDefinition> capabilities = new HashMap<>();
- Either<Map<String, CapabilityDefinition>, StorageOperationStatus> result = null;
- Set<String> caseInsensitiveCapabilityNames = new HashSet<>();
-
- try {
- TitanOperationStatus status = getAllCapabilitiesRecusive(NodeTypeEnum.Resource, resourceId, recursively, capabilities, caseInsensitiveCapabilityNames, inTransaction);
- if (!status.equals(TitanOperationStatus.OK)) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- result = Either.left(capabilities);
- return result;
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- public TitanOperationStatus getAllCapabilitiesRecusive(NodeTypeEnum nodeType, String resourceId, boolean recursively, Map<String, CapabilityDefinition> capabilities, Set<String> caseInsensitiveCapabilityNames, boolean inTransaction) {
-
- TitanOperationStatus findStatus;
-
- if (recursively) {
- findStatus = findAllCapabilitiesRecursively(resourceId, capabilities, caseInsensitiveCapabilityNames);
-
- } else {
- findStatus = getCapabilitisOfResourceOnly(resourceId, capabilities, caseInsensitiveCapabilityNames);
- }
- if (!findStatus.equals(TitanOperationStatus.OK)) {
- return findStatus;
- }
-
- List<String> derivedFromList = new ArrayList<>();
- TitanOperationStatus fillResourceDerivedListFromGraph = fillResourceDerivedListFromGraph(resourceId, derivedFromList);
- if (!fillResourceDerivedListFromGraph.equals(TitanOperationStatus.OK)) {
- log.debug("fail to find all valid sources of capability. status = {}", fillResourceDerivedListFromGraph.name());
- return fillResourceDerivedListFromGraph;
- }
- capabilities.forEach((name, capability) -> capability.setCapabilitySources(derivedFromList));
- return TitanOperationStatus.OK;
- }
-
- protected TitanOperationStatus findAllCapabilitiesRecursively(String resourceId, Map<String, CapabilityDefinition> capabilities, Set<String> caseInsensitiveCapabilityNames) {
-
- TitanOperationStatus resourceCapabilitiesStatus = getCapabilitisOfResourceOnly(resourceId, capabilities, caseInsensitiveCapabilityNames);
-
- if (!resourceCapabilitiesStatus.equals(TitanOperationStatus.OK)) {
- return resourceCapabilitiesStatus;
- }
-
- Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
- ResourceMetadataData.class);
-
- if (parentNodes.isRight()) {
- TitanOperationStatus parentNodesStatus = parentNodes.right().value();
- if (!parentNodesStatus.equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("Failed to find parent capabilities of resource {}. status is {}", resourceId, parentNodesStatus);
- BeEcompErrorManager.getInstance().logBeFailedFindParentError("Fetch parent capabilities", resourceId, String.valueOf(parentNodesStatus));
- return parentNodesStatus;
- }
- }
- if (parentNodes.isLeft()) {
- ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value();
- String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId();
- TitanOperationStatus addParentIntStatus = findAllCapabilitiesRecursively(parentUniqueId, capabilities, caseInsensitiveCapabilityNames);
-
- if (addParentIntStatus != TitanOperationStatus.OK) {
- log.debug("Failed to fetch all capabilities of resource {}", parentUniqueId);
- return addParentIntStatus;
- }
- }
- return TitanOperationStatus.OK;
- }
-
- private TitanOperationStatus getCapabilitisOfResourceOnly(String resourceId, Map<String, CapabilityDefinition> capabilities, Set<String> caseInsensitiveCapabilityNames) {
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> allCapabilitiesRes = getAllCapabilitiesPairs(resourceId);
- if (allCapabilitiesRes.isRight()) {
- TitanOperationStatus status = allCapabilitiesRes.right().value();
- log.debug("After fetching all capabilities of resource {}. status is {}", resourceId, status);
- if (status.equals(TitanOperationStatus.NOT_FOUND)) {
- status = TitanOperationStatus.OK;
- }
- return status;
- }
-
- List<ImmutablePair<CapabilityData, GraphEdge>> capabilityPairs = allCapabilitiesRes.left().value();
-
- if (capabilityPairs != null) {
- for (ImmutablePair<CapabilityData, GraphEdge> capabilityPair : capabilityPairs) {
- CapabilityData capabilityData = capabilityPair.getKey();
- GraphEdge graphEdge = capabilityPair.getValue();
- Map<String, Object> edgeProps = graphEdge.getProperties();
- if (edgeProps != null) {
- String capabilityName = (String) edgeProps.get(GraphPropertiesDictionary.NAME.getProperty());
- if (capabilityName == null) {
- log.error("Capability name was not found for capability {}", capabilityData.getUniqueId());
- return TitanOperationStatus.INVALID_ELEMENT;
- }
- Either<CapabilityDefinition, TitanOperationStatus> capabilityDefRes = getCapabilityByCapabilityData(capabilityData);
- if (capabilityDefRes.isRight()) {
- TitanOperationStatus status = capabilityDefRes.right().value();
- return status;
- }
- CapabilityDefinition capabilityDefinition = capabilityDefRes.left().value();
- capabilityDefinition.setOwnerId(resourceId);
- log.debug("Before adding capability {} with definition {} to result.", capabilityName, capabilityDefinition);
- // US631462
- if (caseInsensitiveCapabilityNames.contains(capabilityName.toLowerCase())) {
- log.debug("The capability {} was already defined in derived resource (case insensitive). Ignore {} from resource {}", capabilityName, capabilityName, resourceId);
- } else {
- capabilities.put(capabilityName, capabilityDefinition);
- caseInsensitiveCapabilityNames.add(capabilityName.toLowerCase());
- }
- } else {
- log.debug("Capability name was not found for capability {}", capabilityData.getUniqueId());
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", capabilityData.getUniqueId(), String.valueOf(TitanOperationStatus.INVALID_ELEMENT));
- return TitanOperationStatus.INVALID_ELEMENT;
- }
-
- }
- }
- return TitanOperationStatus.OK;
- }
-
- @Override
- public Either<CapabilityDefinition, StorageOperationStatus> getCapability(String uniqueId, boolean inTransaction) {
-
- Either<CapabilityDefinition, StorageOperationStatus> result = null;
-
- try {
- Either<CapabilityData, TitanOperationStatus> capabiltyRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), uniqueId, CapabilityData.class);
- if (capabiltyRes.isRight()) {
- TitanOperationStatus status = capabiltyRes.right().value();
- log.debug("Failed to retrieve capability {} from graph. status is {}", uniqueId, status);
-
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", uniqueId, String.valueOf(status));
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- CapabilityData capabilityData = capabiltyRes.left().value();
- CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
- capabilityDefinition.setDescription(capabilityData.getDescription());
- capabilityDefinition.setUniqueId(capabilityData.getUniqueId());
- capabilityDefinition.setValidSourceTypes(capabilityData.getValidSourceTypes());
- capabilityDefinition.setMinOccurrences(capabilityData.getMinOccurrences());
- capabilityDefinition.setMaxOccurrences(capabilityData.getMaxOccurrences());
-
- Either<CapabilityTypeData, TitanOperationStatus> capabilityTypeRes = getCapabilityTypeOfCapability(uniqueId);
- if (capabilityTypeRes.isRight()) {
- TitanOperationStatus status = capabilityTypeRes.right().value();
- log.debug("Failed to retrieve capability type of capability {}. status is {}", uniqueId, status);
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", uniqueId, String.valueOf(status));
-
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- CapabilityTypeData capabilityTypeData = capabilityTypeRes.left().value();
- capabilityDefinition.setType(capabilityTypeData.getCapabilityTypeDataDefinition().getType());
-
- Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), uniqueId, GraphEdgeLabels.CAPABILITY,
- NodeTypeEnum.Resource, ResourceMetadataData.class);
- if (parentNode.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentNode.right().value()));
- } else {
- ImmutablePair<ResourceMetadataData, GraphEdge> pair = parentNode.left().value();
- capabilityDefinition.setOwnerId(pair.left.getMetadataDataDefinition().getUniqueId());
- List<String> derivedFromList = new ArrayList<>();
- TitanOperationStatus fillResourceDerivedListFromGraph = fillResourceDerivedListFromGraph(pair.left.getMetadataDataDefinition().getUniqueId(), derivedFromList);
- if (fillResourceDerivedListFromGraph.equals(TitanOperationStatus.OK)) {
- capabilityDefinition.setCapabilitySources(derivedFromList);
- }
- }
-
- Either<List<PropertyDefinition>, TitanOperationStatus> getPropertiesRes = getPropertiesOfCapability(uniqueId, capabilityTypeData.getCapabilityTypeDataDefinition().getType());
- if (getPropertiesRes.isRight() && !getPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- TitanOperationStatus status = getPropertiesRes.right().value();
- log.debug("Failed to retrieve properties of capability {}. status is {}", uniqueId, status);
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Properties of Capability", uniqueId, String.valueOf(status));
-
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- if (getPropertiesRes.isLeft()) {
- List<ComponentInstanceProperty> properties = new ArrayList<>();
- for (PropertyDefinition property : getPropertiesRes.left().value()) {
- properties.add(new ComponentInstanceProperty(property, null, null));
- }
- capabilityDefinition.setProperties(properties);
- }
- result = Either.left(capabilityDefinition);
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- private TitanOperationStatus fillResourceDerivedListFromGraph(String uniqueId, List<String> derivedFromList) {
-
- Either<ResourceMetadataData, TitanOperationStatus> resourceNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId, ResourceMetadataData.class);
-
- if (resourceNode.isRight()) {
- TitanOperationStatus parentNodesStatus = resourceNode.right().value();
- if (!parentNodesStatus.equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("Failed to find resource {} . status is {}", uniqueId, parentNodesStatus);
- return parentNodesStatus;
- }
- }
-
- derivedFromList.add(((ResourceMetadataDataDefinition) resourceNode.left().value().getMetadataDataDefinition()).getToscaResourceName());
- Either<List<ImmutablePair<ResourceMetadataData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId, GraphEdgeLabels.DERIVED_FROM,
- NodeTypeEnum.Resource, ResourceMetadataData.class);
-
- if (childrenNodes.isRight() && (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND)) {
- return childrenNodes.right().value();
- } else if (childrenNodes.isLeft()) {
-
- List<ImmutablePair<ResourceMetadataData, GraphEdge>> pairList = childrenNodes.left().value();
- for (ImmutablePair<ResourceMetadataData, GraphEdge> pair : pairList) {
- return fillResourceDerivedListFromGraph(pair.left.getMetadataDataDefinition().getUniqueId(), derivedFromList);
- }
- }
- return TitanOperationStatus.OK;
- }
-
- public Either<CapabilityDefinition, TitanOperationStatus> getCapabilityByCapabilityData(CapabilityData capabilityData) {
-
- Either<CapabilityDefinition, TitanOperationStatus> result;
-
- CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
- capabilityDefinition.setDescription(capabilityData.getDescription());
- capabilityDefinition.setUniqueId(capabilityData.getUniqueId());
- capabilityDefinition.setValidSourceTypes(capabilityData.getValidSourceTypes());
- capabilityDefinition.setMinOccurrences(capabilityData.getMinOccurrences());
- capabilityDefinition.setMaxOccurrences(capabilityData.getMaxOccurrences());
-
- String capabilityUid = capabilityData.getUniqueId();
- Either<CapabilityTypeData, TitanOperationStatus> capabilityTypeRes = getCapabilityTypeOfCapability(capabilityUid);
- if (capabilityTypeRes.isRight()) {
- TitanOperationStatus status = capabilityTypeRes.right().value();
- log.debug("Failed to retrieve capability type of capability {} . status is {}", capabilityUid, status);
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", capabilityUid, String.valueOf(status));
-
- return Either.right(status);
- }
-
- CapabilityTypeData capabilityTypeData = capabilityTypeRes.left().value();
- capabilityDefinition.setType(capabilityTypeData.getCapabilityTypeDataDefinition().getType());
-
- Either<List<PropertyDefinition>, TitanOperationStatus> capabilityPropertiesRes = getPropertiesOfCapability(capabilityUid, capabilityDefinition.getType());
- if (capabilityPropertiesRes.isRight() && !capabilityPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- TitanOperationStatus status = capabilityPropertiesRes.right().value();
- log.debug("Failed to retrieve properties of capability {} . status is {}", capabilityUid, status);
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", capabilityUid, String.valueOf(status));
-
- result = Either.right(status);
- return result;
- }
- if (capabilityPropertiesRes.isLeft()) {
- List<ComponentInstanceProperty> properties = new ArrayList<>();
- for (PropertyDefinition property : capabilityPropertiesRes.left().value()) {
- properties.add(new ComponentInstanceProperty(property, null, null));
- }
- capabilityDefinition.setProperties(properties);
- }
- result = Either.left(capabilityDefinition);
- return result;
- }
-
- public Either<CapabilityDefinition, TitanOperationStatus> getCapabilityByCapabilityData(TitanVertex capabilityDataVertex) {
-
- Either<CapabilityDefinition, TitanOperationStatus> result;
-
- CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
- Map<String, Object> props = titanGenericDao.getProperties(capabilityDataVertex);
- CapabilityData capabilityData = GraphElementFactory.createElement((String) props.get(GraphPropertiesDictionary.LABEL.getProperty()), GraphElementTypeEnum.Node, props, CapabilityData.class);
- capabilityDefinition.setDescription(capabilityData.getDescription());
- capabilityDefinition.setUniqueId(capabilityData.getUniqueId());
- capabilityDefinition.setValidSourceTypes(capabilityData.getValidSourceTypes());
- capabilityDefinition.setMinOccurrences(capabilityData.getMinOccurrences());
- capabilityDefinition.setMaxOccurrences(capabilityData.getMaxOccurrences());
-
- String capabilityUid = capabilityData.getUniqueId();
- Either<CapabilityTypeData, TitanOperationStatus> capabilityTypeRes = getCapabilityTypeOfCapability(capabilityUid);
- if (capabilityTypeRes.isRight()) {
- TitanOperationStatus status = capabilityTypeRes.right().value();
- log.debug("Failed to retrieve capability type of capability {} . status is {}", capabilityUid, status);
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", capabilityUid, String.valueOf(status));
-
- return Either.right(status);
- }
-
- CapabilityTypeData capabilityTypeData = capabilityTypeRes.left().value();
- capabilityDefinition.setType(capabilityTypeData.getCapabilityTypeDataDefinition().getType());
-
- Either<List<PropertyDefinition>, TitanOperationStatus> capabilityPropertiesRes = getPropertiesOfCapability(capabilityUid, capabilityDefinition.getType());
- if (capabilityPropertiesRes.isRight() && !capabilityPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- TitanOperationStatus status = capabilityPropertiesRes.right().value();
- log.debug("Failed to retrieve properties of capability {} . status is {}", capabilityUid, status);
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", capabilityUid, String.valueOf(status));
-
- result = Either.right(status);
- return result;
- }
- if (capabilityPropertiesRes.isLeft()) {
- List<ComponentInstanceProperty> properties = new ArrayList<>();
- for (PropertyDefinition property : capabilityPropertiesRes.left().value()) {
- properties.add(new ComponentInstanceProperty(property, null, null));
- }
- capabilityDefinition.setProperties(properties);
- }
- result = Either.left(capabilityDefinition);
- return result;
- }
-
- public Either<List<PropertyDefinition>, TitanOperationStatus> getPropertiesOfCapability(String capabilityUid, String capabilityType) {
- log.debug("Before getting properties of capability {} from graph " , capabilityUid);
-
- List<PropertyDefinition> properties;
- Either<List<PropertyDefinition>, TitanOperationStatus> result = null;
- Either<Map<String, PropertyDefinition>, TitanOperationStatus> getPropertiesOfCapabilityTypeRes = null;
- Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> getPropertiesOfCapabilityRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, GraphEdgeLabels.PROPERTY,
- NodeTypeEnum.Property, PropertyData.class);
- if (getPropertiesOfCapabilityRes.isRight() && !getPropertiesOfCapabilityRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- TitanOperationStatus status = getPropertiesOfCapabilityRes.right().value();
- log.debug("failed to get properties of capability with id {}. status={}", capabilityUid, status);
- result = Either.right(status);
- }
- if (result == null) {
- String capabilityTypeUid = UniqueIdBuilder.buildCapabilityTypeUid(capabilityType);
- getPropertiesOfCapabilityTypeRes = getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeUid);
- if (getPropertiesOfCapabilityTypeRes.isRight() && !getPropertiesOfCapabilityTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- TitanOperationStatus status = getPropertiesOfCapabilityTypeRes.right().value();
- log.error("Failed to retrieve properties for capability type {} from graph. status is {}", capabilityType, status);
- result = Either.right(status);
- }
- }
- if (result == null) {
- result = getPropertiesOfCapabilityTypeRes.isRight()
- ? (getPropertiesOfCapabilityRes.isRight() ? Either.right(TitanOperationStatus.NOT_FOUND)
- : Either.left(getPropertiesOfCapabilityRes.left().value().stream().map(p -> propertyOperation.convertPropertyDataToPropertyDefinition(p.getKey(), null, capabilityUid)).collect(Collectors.toList())))
- : (getPropertiesOfCapabilityRes.isRight() ? Either.left(getPropertiesOfCapabilityTypeRes.left().value().values().stream().collect(Collectors.toList())) : null);
- }
- if (result == null) {
- Map<String, PropertyDefinition> propertiesOfCapabilityType = getPropertiesOfCapabilityTypeRes.left().value();
- properties = getPropertiesOfCapabilityRes.left().value().stream()
- .map(p -> propertyOperation.convertPropertyDataToPropertyDefinition(p.getKey(), (String) p.getRight().getProperties().get(GraphPropertiesDictionary.NAME.getProperty()), capabilityUid)).collect(Collectors.toList());
- properties.stream().forEach(p -> propertiesOfCapabilityType.remove(p.getName()));
- properties.addAll(propertiesOfCapabilityType.values());
- result = Either.left(properties);
- }
- return result;
- }
-
- @Override
- public Either<CapabilityTypeData, TitanOperationStatus> getCapabilityTypeOfCapability(String uniqueId) {
-
- Either<ImmutablePair<CapabilityTypeData, GraphEdge>, TitanOperationStatus> capabilityTypeRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), uniqueId, GraphEdgeLabels.TYPE_OF, NodeTypeEnum.CapabilityType,
- CapabilityTypeData.class);
-
- if (capabilityTypeRes.isRight()) {
- TitanOperationStatus status = capabilityTypeRes.right().value();//
- log.debug("Cannot find capability type associated with capability {}. status is {}", uniqueId, status);
- BeEcompErrorManager.getInstance().logBeFailedFindAssociationError("Fetch Capability type", NodeTypeEnum.CapabilityType.getName(), uniqueId, String.valueOf(status));
- return Either.right(capabilityTypeRes.right().value());
- }
-
- CapabilityTypeData capabilityTypeData = capabilityTypeRes.left().value().getKey();
-
- return Either.left(capabilityTypeData);
-
- }
-
- @Override
- public Either<CapabilityDefinition, StorageOperationStatus> getCapability(String capabilityName, String resourceId) {
- return getCapability(UniqueIdBuilder.buildCapabilityUid(resourceId, capabilityName));
- }
-
- @Override
- public Either<CapabilityDefinition, StorageOperationStatus> getCapability(String capabilityName, String resourceId, boolean inTransaction) {
- return getCapability(UniqueIdBuilder.buildCapabilityUid(resourceId, capabilityName), inTransaction);
- }
-
- @Override
- public Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getAllCapabilitiesPairs(String resourceId) {
-
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> capabilitiesNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.CAPABILITY,
- NodeTypeEnum.Capability, CapabilityData.class);
-
- log.debug("After looking for all capabilities under resource {}. status is {}" , resourceId , capabilitiesNodes);
- if (capabilitiesNodes.isRight()) {
- TitanOperationStatus status = capabilitiesNodes.right().value();
- return Either.right(status);
- }
-
- List<ImmutablePair<CapabilityData, GraphEdge>> capabilities = capabilitiesNodes.left().value();
- if (capabilities == null || true == capabilities.isEmpty()) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- return Either.left(capabilitiesNodes.left().value());
- }
-
- private Either<CapabilityData, TitanOperationStatus> addCapabilityToResource(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition) {
-
- log.debug("Going to add capability {} [ {} ] to resource uid {}" , capabilityName, capabilityDefinition, resourceId);
-
- Either<CapabilityData, TitanOperationStatus> createCapRes = createCapability(resourceId, capabilityName, capabilityDefinition);
-
- log.debug("After creating capability node in graph. status is {}", createCapRes);
- if (createCapRes.isRight()) {
- TitanOperationStatus status = createCapRes.right().value();
- log.error("Failed to create capability data node in graph. status is {}", status);
- return Either.right(status);
- }
- CapabilityData capabilityData = createCapRes.left().value();
-
- String capabilityType = capabilityDefinition.getType();
-
- log.debug("Going to associate capability {} to its capabilityType {}", capabilityName, capabilityType);
-
- Either<GraphRelation, TitanOperationStatus> associateCapabilityTypeRes = associateCapabilityToCapabilityType(capabilityData, capabilityType);
- log.debug("After associating capability {} to its capabilityType {}. status is {}", capabilityName, capabilityType, associateCapabilityTypeRes);
- if (associateCapabilityTypeRes.isRight()) {
- TitanOperationStatus status = associateCapabilityTypeRes.right().value();
- log.error("Failed to associate capability {} to its capabilityType {} in graph. status is {} ", capabilityName, capabilityType, status);
-
- return Either.right(status);
- }
- List<ComponentInstanceProperty> ciProperties = capabilityDefinition.getProperties();
- if (ciProperties != null && !ciProperties.isEmpty()) {
- List<PropertyDefinition> properties = ciProperties.stream().map(prop -> new PropertyDefinition(prop)).collect(Collectors.toList());
- Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesRes = addPropertiesToCapability(capabilityData, capabilityType, properties);
- if (addPropertiesRes.isRight()) {
- TitanOperationStatus operationStatus = addPropertiesRes.right().value();
- return Either.right(operationStatus);
- }
- }
-
- Either<GraphRelation, TitanOperationStatus> associateResourceRes = associateResourceToCapability(resourceId, capabilityName, capabilityData);
- if (associateResourceRes.isRight()) {
- TitanOperationStatus status = associateResourceRes.right().value();
- log.error("Failed to associate resource {} to capability {}. status is {}", resourceId, capabilityData, status);
- return Either.right(status);
- }
-
- return Either.left(capabilityData);
-
- }
-
- private TitanOperationStatus addCapabilityToResource(TitanVertex metadataVertex, String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition) {
-
- log.debug("Going to add capability {} [ {} ] to resource uid {}", capabilityName, capabilityDefinition, resourceId);
-
- Either<TitanVertex, TitanOperationStatus> createCapRes = createCapabilityVertex(resourceId, capabilityName, capabilityDefinition);
-
- log.debug("After creating capability node in graph. status is {}", createCapRes);
- if (createCapRes.isRight()) {
- TitanOperationStatus status = createCapRes.right().value();
- log.error("Failed to create capability data node in graph. status is {}", status);
- return status;
- }
- TitanVertex capabilityVertex = createCapRes.left().value();
-
- String capabilityType = capabilityDefinition.getType();
-
- log.debug("Going to associate capability {} to its capabilityType {}", capabilityName, capabilityType);
-
- TitanOperationStatus associateCapabilityTypeRes = associateCapabilityToCapabilityType(capabilityVertex, capabilityType);
- log.debug("After associating capability {} to its capabilityType {}. status is {}", capabilityName, capabilityType, associateCapabilityTypeRes);
- if (!associateCapabilityTypeRes.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate capability {} to its capabilityType {} in graph. status is {} ", capabilityName, capabilityType, associateCapabilityTypeRes);
- return associateCapabilityTypeRes;
- }
- List<ComponentInstanceProperty> ciProperties = capabilityDefinition.getProperties();
- if (ciProperties != null && !ciProperties.isEmpty()) {
- String capabiltyId = (String) titanGenericDao.getProperty(capabilityVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- List<PropertyDefinition> properties = ciProperties.stream().map(prop -> new PropertyDefinition(prop)).collect(Collectors.toList());
- TitanOperationStatus addPropertiesRes = addPropertiesToCapability(capabilityVertex, capabilityType, properties, capabiltyId);
- if (!addPropertiesRes.equals(TitanOperationStatus.OK)) {
- return addPropertiesRes;
- }
- }
-
- TitanOperationStatus associateResourceRes = associateResourceToCapability(resourceId, capabilityName, capabilityVertex, metadataVertex);
- if (!associateResourceRes.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate resource{} to capability {}. status is {} ", resourceId, capabilityName, associateResourceRes);
- }
-
- return associateResourceRes;
-
- }
-
- private Either<GraphRelation, TitanOperationStatus> associateCapabilityToCapabilityType(CapabilityData capabilityData, String capabilityType) {
- UniqueIdData capabilityTypeIdData = new UniqueIdData(NodeTypeEnum.CapabilityType, UniqueIdBuilder.buildCapabilityTypeUid(capabilityType));
- log.debug("Before associating {} to capability type {}.", capabilityData, capabilityType);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(capabilityData, capabilityTypeIdData, GraphEdgeLabels.TYPE_OF, null);
- log.debug("After associating {} to capability type {}. status is {}" , capabilityData, capabilityType, createRelResult);
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate capability {} to capability type {} in graph. status is {}", capabilityData, capabilityTypeIdData, operationStatus);
- return Either.right(operationStatus);
- }
- return Either.left(createRelResult.left().value());
-
- }
-
- private TitanOperationStatus associateCapabilityToCapabilityType(TitanVertex capabilityVertex, String capabilityType) {
-
- UniqueIdData capabilityTypeIdData = new UniqueIdData(NodeTypeEnum.CapabilityType, UniqueIdBuilder.buildCapabilityTypeUid(capabilityType));
-
- log.debug("Before associating {} to capability type {}.", capabilityVertex, capabilityType);
- TitanOperationStatus createRelResult = titanGenericDao.createEdge(capabilityVertex, capabilityTypeIdData, GraphEdgeLabels.TYPE_OF, null);
- log.trace("After associating {} to capability type {}. status is {}", capabilityVertex, capabilityType, createRelResult);
- if (!createRelResult.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate capability {} to capability type {} in graph. status is {}", capabilityVertex, capabilityTypeIdData, createRelResult);
- }
- return createRelResult;
- }
-
- private Either<GraphRelation, TitanOperationStatus> associateResourceToCapability(String resourceId, String capabilityName, CapabilityData capabilityData) {
-
- UniqueIdData resourceIdData = new UniqueIdData(NodeTypeEnum.Resource, resourceId);
-
- log.debug("Before associating resource {} to capability {}.", resourceId, capabilityData);
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceIdData, capabilityData, GraphEdgeLabels.CAPABILITY, props);
- log.debug("After associating resource {} to capability {}. status is {}" , resourceId, capabilityData, createRelResult);
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate resource {} to capability {} in graph. status is {}", resourceId, capabilityData, operationStatus);
- return Either.right(operationStatus);
- }
-
- return Either.left(createRelResult.left().value());
-
- }
-
- private TitanOperationStatus associateResourceToCapability(String resourceId, String capabilityName, TitanVertex capabilityVertex, TitanVertex resourceVertex) {
-
- log.debug("Before associating resource {} to capability {}.", resourceId, capabilityName);
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName);
- TitanOperationStatus createRelResult = titanGenericDao.createEdge(resourceVertex, capabilityVertex, GraphEdgeLabels.CAPABILITY, props);
- log.debug("After associating resource {} to capability {}. status is {}", resourceId, capabilityName, createRelResult);
- if (!createRelResult.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate resource {} to capability {} in graph. status is {}", resourceId, capabilityName, createRelResult);
- }
-
- return createRelResult;
-
- }
-
- /**
- *
- * create capability node in the graph
- *
- * @param resourceId
- * @param capabilityName
- * @param capabilityDefinition
- * @return
- */
- private Either<CapabilityData, TitanOperationStatus> createCapability(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition) {
-
- CapabilityData capabilityData = new CapabilityData();
- String uid = UniqueIdBuilder.buildCapabilityUid(resourceId, capabilityName);
- capabilityData.setUniqueId(uid);
- Long creationTime = System.currentTimeMillis();
- capabilityData.setCreationTime(creationTime);
- capabilityData.setModificationTime(creationTime);
- capabilityData.setValidSourceTypes(capabilityDefinition.getValidSourceTypes());
- capabilityData.setMinOccurrences(capabilityDefinition.getMinOccurrences());
- capabilityData.setMaxOccurrences(capabilityDefinition.getMaxOccurrences());
- capabilityData.setDescription(capabilityDefinition.getDescription());
-
- Either<CapabilityData, TitanOperationStatus> createNode = titanGenericDao.createNode(capabilityData, CapabilityData.class);
-
- log.debug("After creating capability node in the graph. status is {}", createNode);
-
- return createNode;
- }
-
- private Either<TitanVertex, TitanOperationStatus> createCapabilityVertex(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition) {
-
- CapabilityData capabilityData = new CapabilityData();
- String uid = UniqueIdBuilder.buildCapabilityUid(resourceId, capabilityName);
- capabilityData.setUniqueId(uid);
- Long creationTime = System.currentTimeMillis();
- capabilityData.setCreationTime(creationTime);
- capabilityData.setModificationTime(creationTime);
- capabilityData.setValidSourceTypes(capabilityDefinition.getValidSourceTypes());
- capabilityData.setMinOccurrences(capabilityDefinition.getMinOccurrences());
- capabilityData.setMaxOccurrences(capabilityDefinition.getMaxOccurrences());
- capabilityData.setDescription(capabilityDefinition.getDescription());
-
- Either<TitanVertex, TitanOperationStatus> createNode = titanGenericDao.createNode(capabilityData);
-
- log.debug("After creating capability node in the graph. status is {}", createNode);
-
- return createNode;
- }
@Override
- public Either<CapabilityDefinition, StorageOperationStatus> addCapability(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition) {
-
- return addCapability(resourceId, capabilityName, capabilityDefinition, false);
-
- }
-
- public StorageOperationStatus deleteCapabilityFromGraph(String capabilityUid) {
-
- TitanOperationStatus resultStatus = null;
-
- Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesStatus = deletePropertiesOfCapability(capabilityUid);
-
- if (deletePropertiesStatus.isRight() && !deletePropertiesStatus.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- resultStatus = deletePropertiesStatus.right().value();
- }
- if (resultStatus == null) {
- log.debug("Before deleting capability from graph {}" , capabilityUid);
- Either<CapabilityData, TitanOperationStatus> deleteNodeStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, CapabilityData.class);
- if (deleteNodeStatus.isRight()) {
- resultStatus = deleteNodeStatus.right().value();
- }
- }
- if (resultStatus != null) {
- log.debug("failed to delete capability with id {}. status={}", capabilityUid, resultStatus);
- BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete capability", capabilityUid, String.valueOf(resultStatus));
- return DaoStatusConverter.convertTitanStatusToStorageStatus(resultStatus);
- }
- return StorageOperationStatus.OK;
- }
-
- public Either<Map<String, CapabilityDefinition>, StorageOperationStatus> deleteAllCapabilities(String resourceId, boolean inTransaction) {
-
- Either<Map<String, CapabilityDefinition>, StorageOperationStatus> result = null;
- try {
-
- Either<Map<String, CapabilityDefinition>, TitanOperationStatus> deleteAllRes = deleteAllCapabilitiesOfResource(resourceId);
- if (deleteAllRes.isRight()) {
- TitanOperationStatus status = deleteAllRes.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- log.debug("Failed to delete capabilities of resource {}. status is {}", resourceId, status);
- }
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- Map<String, CapabilityDefinition> value = deleteAllRes.left().value();
- result = Either.left(value);
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- public Either<Map<String, CapabilityDefinition>, StorageOperationStatus> deleteAllCapabilities(String resourceId) {
-
- return deleteAllCapabilities(resourceId, false);
-
- }
-
- private Either<Map<String, CapabilityDefinition>, TitanOperationStatus> deleteAllCapabilitiesOfResource(String resourceId) {
- TitanOperationStatus resultStatus = null;
- Map<String, CapabilityDefinition> capabilities = new HashMap<>();
- Set<String> caseInsensitiveCapabilityNames = new HashSet<>();
- TitanOperationStatus capabilitisRes = getCapabilitisOfResourceOnly(resourceId, capabilities, caseInsensitiveCapabilityNames);
- if (capabilitisRes != TitanOperationStatus.OK) {
- return Either.right(capabilitisRes);
- }
-
- if (capabilities.isEmpty()) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- for (Entry<String, CapabilityDefinition> entry : capabilities.entrySet()) {
- CapabilityDefinition capabilityDefinition = entry.getValue();
- String capabilityUid = capabilityDefinition.getUniqueId();
-
- log.debug("Before deleting properties of capability {} from graph " , capabilityUid);
-
- Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesStatus = deletePropertiesOfCapability(capabilityUid);
- if (deletePropertiesStatus.isRight() && !deletePropertiesStatus.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- resultStatus = deletePropertiesStatus.right().value();
- }
- if (resultStatus == null) {
- Either<CapabilityData, TitanOperationStatus> deleteNodeRes = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, CapabilityData.class);
- if (deleteNodeRes.isRight()) {
- resultStatus = deleteNodeRes.right().value();
- }
- }
- if (resultStatus != null) {
- log.debug("Failed to delete capability {} of resource {}", capabilityUid, resourceId);
- BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete capability", capabilityUid, String.valueOf(resultStatus));
- return Either.right(resultStatus);
- }
- }
-
- return Either.left(capabilities);
-
- }
-
- public Map<String, List<CapabilityDefinition>> convertCapabilityMap(Map<String, CapabilityDefinition> capabilityMap, String ownerId, String ownerName) {
-
- Map<String, List<CapabilityDefinition>> typeToRequirementMap = new HashMap<>();
- capabilityMap.forEach((capabilityName, capability) -> {
- capability.setName(capabilityName);
- if (typeToRequirementMap.containsKey(capability.getType())) {
- typeToRequirementMap.get(capability.getType()).add(capability);
- } else {
- List<CapabilityDefinition> list = new ArrayList<>();
- list.add(capability);
- typeToRequirementMap.put(capability.getType(), list);
- }
- });
- return typeToRequirementMap;
- }
-
- public TitanOperationStatus getCapabilitySourcesList(String resourceId, List<String> derivedFromList) {
- Map<String, Object> propertiesToMatch = new HashMap<>();
- propertiesToMatch.put(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId);
- Either<List<ResourceMetadataData>, TitanOperationStatus> getResponse = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class);
- if (getResponse.isRight()) {
- return getResponse.right().value();
- } else {
- String toscaResourceName = ((ResourceMetadataDataDefinition) getResponse.left().value().get(0).getMetadataDataDefinition()).getToscaResourceName();
- derivedFromList.add(toscaResourceName);
- }
-
- Either<List<ImmutablePair<ResourceMetadataData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM,
- NodeTypeEnum.Resource, ResourceMetadataData.class);
-
- while (childrenNodes.isLeft()) {
-
- List<ImmutablePair<ResourceMetadataData, GraphEdge>> pairList = childrenNodes.left().value();
- ResourceMetadataData left = pairList.get(0).left;
- derivedFromList.add(((ResourceMetadataDataDefinition) left.getMetadataDataDefinition()).getToscaResourceName());
- String id = left.getMetadataDataDefinition().getUniqueId();
- childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), id, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class);
- }
- return TitanOperationStatus.OK;
- }
-
- private Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapability(CapabilityData capabilityData, String capabilityType, List<PropertyDefinition> properties) {
- String capabilityTypeUid = UniqueIdBuilder.buildCapabilityTypeUid(capabilityType);
- Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesOfCapabilityTypeRes = getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeUid);
- if (allPropertiesOfCapabilityTypeRes.isRight() && !allPropertiesOfCapabilityTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- TitanOperationStatus operationStatus = allPropertiesOfCapabilityTypeRes.right().value();
- log.error("Failed to retrieve properties for capability type {} from graph. status is {}", capabilityType, operationStatus);
- return Either.right(operationStatus);
- }
-
- Map<String, PropertyDefinition> propertiesOfCapabilityType = null;
-
- if (allPropertiesOfCapabilityTypeRes.isLeft() && allPropertiesOfCapabilityTypeRes.left() != null && !allPropertiesOfCapabilityTypeRes.left().value().isEmpty()) {
-
- propertiesOfCapabilityType = allPropertiesOfCapabilityTypeRes.left().value();
- Either<List<PropertyDefinition>, TitanOperationStatus> validateAndReducePropertiesRes = validatePropertyUniqueness(propertiesOfCapabilityType, properties);
- if (validateAndReducePropertiesRes.isRight()) {
- TitanOperationStatus operationStatus = validateAndReducePropertiesRes.right().value();
- log.error("Failed to add properties to capability {} in graph. status is {}", capabilityData.getUniqueId(), operationStatus);
- return Either.right(operationStatus);
- }
- }
-
- Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapabilityRes = propertyOperation.addPropertiesToElementType(capabilityData.getUniqueId(), NodeTypeEnum.Capability, properties);
- if (addPropertiesToCapabilityRes.isRight()) {
- TitanOperationStatus operationStatus = addPropertiesToCapabilityRes.right().value();
- log.error("Failed to add properties to capability {} in graph. status is {}", capabilityData.getUniqueId(), operationStatus);
- return Either.right(operationStatus);
- }
- return Either.left(addPropertiesToCapabilityRes.left().value());
- }
-
- private TitanOperationStatus addPropertiesToCapability(TitanVertex capabilityVertex, String capabilityType, List<PropertyDefinition> properties, String uniqueId) {
- String capabilityTypeUid = UniqueIdBuilder.buildCapabilityTypeUid(capabilityType);
- Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesOfCapabilityTypeRes = getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeUid);
- if (allPropertiesOfCapabilityTypeRes.isRight() && !allPropertiesOfCapabilityTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- TitanOperationStatus operationStatus = allPropertiesOfCapabilityTypeRes.right().value();
- log.error("Failed to retrieve properties for capability type {} from graph. status is {}", capabilityType, operationStatus);
- return operationStatus;
- }
- Map<String, PropertyDefinition> propertiesOfCapabilityType = null;
-
- if (allPropertiesOfCapabilityTypeRes.isLeft() && allPropertiesOfCapabilityTypeRes.left() != null && !allPropertiesOfCapabilityTypeRes.left().value().isEmpty()) {
-
- propertiesOfCapabilityType = allPropertiesOfCapabilityTypeRes.left().value();
- Either<List<PropertyDefinition>, TitanOperationStatus> validateAndReducePropertiesRes = validatePropertyUniqueness(propertiesOfCapabilityType, properties);
- if (validateAndReducePropertiesRes.isRight()) {
- TitanOperationStatus operationStatus = validateAndReducePropertiesRes.right().value();
- log.error("Failed to add properties to capability {} in graph. status is {}", capabilityVertex, operationStatus);
- return operationStatus;
- }
- }
-
- String capabiltyId = (String) titanGenericDao.getProperty(capabilityVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- TitanOperationStatus addPropertiesToCapabilityRes = propertyOperation.addPropertiesToElementType(capabilityVertex, capabiltyId, NodeTypeEnum.Capability, properties);
- if (!addPropertiesToCapabilityRes.equals(TitanOperationStatus.OK)) {
- log.error("Failed to add properties to capability {} in graph. status is {}", capabiltyId, addPropertiesToCapabilityRes);
- }
- return addPropertiesToCapabilityRes;
- }
-
public Either<List<PropertyDefinition>, TitanOperationStatus> validatePropertyUniqueness(Map<String, PropertyDefinition> propertiesOfCapabilityType, List<PropertyDefinition> properties) {
Either<List<PropertyDefinition>, TitanOperationStatus> result = Either.left(properties);
@@ -1043,119 +117,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit
return result;
}
- public StorageOperationStatus validateUpdateCapabilityProperty(PropertyDefinition property) {
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- return DaoStatusConverter.convertTitanStatusToStorageStatus(allDataTypes.right().value());
- }
- return propertyOperation.validateAndUpdateProperty(property, allDataTypes.left().value());
- }
-
- public StorageOperationStatus validateCapabilityProperties(List<PropertyDefinition> properties) {
- StorageOperationStatus result = StorageOperationStatus.OK;
- for (PropertyDefinition property : properties) {
- result = validateUpdateCapabilityProperty(property);
- if (!result.equals(StorageOperationStatus.OK))
- break;
- }
- return result;
- }
-
- public Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesOfCapability(String capabilityUid) {
- log.debug("Before deleting properties of capability {} from graph " , capabilityUid);
-
- Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesStatus = titanGenericDao.deleteChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, GraphEdgeLabels.PROPERTY,
- NodeTypeEnum.Property, PropertyData.class);
- if (deletePropertiesStatus.isRight()) {
- TitanOperationStatus status = deletePropertiesStatus.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- log.debug("failed to delete properties of capability with id {}. status={}", capabilityUid, status);
- } else {
- log.debug("The Capability with id {} have no Properties. status={}", capabilityUid, status);
- }
- return Either.right(status);
- }
- return Either.left(deletePropertiesStatus.left().value());
- }
-
- @Override
- public Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId, String capabilityType, List<PropertyDefinition> newProperties) {
- return updatePropertiesOfCapability(uniqueId, capabilityType, newProperties, false);
- }
-
@Override
- public Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId, String capabilityType, List<PropertyDefinition> newProperties, boolean inTransaction) {
-
- Either<Map<String, PropertyData>, StorageOperationStatus> result = null;
- try {
- Either<CapabilityData, TitanOperationStatus> capabiltyRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), uniqueId, CapabilityData.class);
- if (capabiltyRes.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(capabiltyRes.right().value()));
- }
- CapabilityData capabilityData = capabiltyRes.left().value();
- if (result == null) {
- StorageOperationStatus propertiesValidationRes = validateCapabilityProperties(newProperties);
- if (!propertiesValidationRes.equals(StorageOperationStatus.OK)) {
- result = Either.right(propertiesValidationRes);
- }
- }
- if (result == null) {
- Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesRes = deletePropertiesOfCapability(uniqueId);
- if (deletePropertiesRes.isRight() && !deletePropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deletePropertiesRes.right().value()));
- }
- }
- if (result == null) {
- Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesRes = addPropertiesToCapability(capabilityData, capabilityType, newProperties);
- if (addPropertiesRes.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertiesRes.right().value()));
- } else {
- result = Either.left(addPropertiesRes.left().value());
- }
- }
- if (result.isRight()) {
- log.debug("Failed to update properties of capability {}. status is {}", uniqueId, result);
- }
- return result;
- } finally {
- if (!inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- public Either<CapabilityData, TitanOperationStatus> getCapabilityRelatedToResourceInstance(String resourceInstanceId, String capabilityUid) {
- TitanOperationStatus error = null;
- CapabilityData capability = null;
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getCapabilitiesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId,
- GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class);
- if (getCapabilitiesRes.isRight()) {
- error = getCapabilitiesRes.right().value();
- log.debug("Failed to retrieve capabilities for resource instance {}. status is {}", resourceInstanceId, error);
- } else {
- List<ImmutablePair<CapabilityData, GraphEdge>> capabilityPairsList = getCapabilitiesRes.left().value();
- List<CapabilityData> capabilityPair = capabilityPairsList.stream().filter(pair -> pair.getLeft().getUniqueId().equals(capabilityUid)).map(pair -> pair.getLeft()).collect(Collectors.toList());
- if (capabilityPair.isEmpty()) {
- error = TitanOperationStatus.NOT_FOUND;
- log.debug("Failed to retrieve capability {} for resource instance {}. status is {}", capabilityUid, resourceInstanceId, error);
- } else {
- capability = capabilityPair.get(0);
- }
- }
- if (error == null) {
- return Either.left(capability);
- }
- return Either.right(error);
- }
-
public Either<Map<String, PropertyDefinition>, TitanOperationStatus> getAllCapabilityTypePropertiesFromAllDerivedFrom(String firstParentType) {
Map<String, PropertyDefinition> allProperies = new HashMap<>();
return getCapabilityTypePropertiesFromDerivedFromRecursively(firstParentType, allProperies);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java
index ddd6017620..203135b31e 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java
@@ -37,6 +37,7 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.operations.api.ICapabilityOperation;
import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.CapabilityTypeData;
@@ -54,7 +55,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab
@Autowired
private PropertyOperation propertyOperation;
@Autowired
- private CapabilityOperation capabilityOperation;
+ private ICapabilityOperation capabilityOperation;
public CapabilityTypeOperation() {
super();
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java
index cb9adeda3f..1ef64aed98 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java
@@ -20,30 +20,15 @@
package org.openecomp.sdc.be.model.operations.impl;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.UUID;
-import java.util.function.Function;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanVertex;
+import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.tinkerpop.gremlin.structure.Direction;
-import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
-import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
@@ -51,74 +36,33 @@ import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
-import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.HeatParameterDefinition;
import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RelationshipImpl;
-import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
-import org.openecomp.sdc.be.model.operations.api.IAttributeOperation;
import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
+import org.openecomp.sdc.be.model.operations.api.IInputsOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
-import org.openecomp.sdc.be.resources.data.ArtifactData;
import org.openecomp.sdc.be.resources.data.AttributeData;
import org.openecomp.sdc.be.resources.data.AttributeValueData;
-import org.openecomp.sdc.be.resources.data.CapabilityData;
-import org.openecomp.sdc.be.resources.data.CapabilityInstData;
import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
-import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
import org.openecomp.sdc.be.resources.data.InputValueData;
import org.openecomp.sdc.be.resources.data.InputsData;
-import org.openecomp.sdc.be.resources.data.PropertyData;
-import org.openecomp.sdc.be.resources.data.PropertyValueData;
-import org.openecomp.sdc.be.resources.data.RelationshipInstData;
-import org.openecomp.sdc.be.resources.data.RelationshipTypeData;
-import org.openecomp.sdc.be.resources.data.RequirementData;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.openecomp.sdc.be.resources.data.UniqueIdData;
-import org.openecomp.sdc.be.resources.data.UserData;
-import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import com.thinkaurelius.titan.core.TitanEdge;
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanVertex;
-import com.thinkaurelius.titan.core.TitanVertexQuery;
-
-import fj.data.Either;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+import java.util.function.Supplier;
@org.springframework.stereotype.Component("component-instance-operation")
public class ComponentInstanceOperation extends AbstractOperation implements IComponentInstanceOperation {
@@ -130,44 +74,17 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
private static Logger log = LoggerFactory.getLogger(ComponentInstanceOperation.class.getName());
@Autowired
- private ResourceOperation resourceOperation;
-
- @Autowired
- private ServiceOperation serviceOperation;
-
- @Autowired
- CapabilityOperation capabilityOperation;
-
- @Autowired
- private CapabilityInstanceOperation capabilityInstanceOperation;
-
- @Autowired
- private RequirementOperation requirementOperation;
-
- @Autowired
- private ArtifactOperation artifactOperation;
-
- @Autowired
TitanGenericDao titanGenericDao;
@Autowired
PropertyOperation propertyOperation;
@Autowired
- InputsOperation inputOperation;
-
- @Autowired
- private IAttributeOperation attributeOperation;
+ private IInputsOperation inputOperation;
@Autowired
private ApplicationDataTypeCache dataTypeCache;
- @Autowired
- protected GroupOperation groupOperation;
-
- @Autowired
- protected GroupInstanceOperation groupInstanceOperation;
-
/**
* FOR TEST ONLY
*
@@ -178,3344 +95,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
@Override
- public Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String parentComponentId, NodeTypeEnum nodeType, String instanceNumber, ComponentInstance componentInstance, NodeTypeEnum compInstNodeType, boolean inTransaction) {
-
- return createComponentInstance(parentComponentId, nodeType, instanceNumber, true, componentInstance, compInstNodeType, false, inTransaction);
-
- }
-
- private Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, boolean isCreateLocgicalName, ComponentInstance componentInstance,
- NodeTypeEnum compInstNodeType, boolean allowDeleted, boolean inTransaction) {
- Either<ComponentInstance, StorageOperationStatus> result = null;
-
- if (!ValidationUtils.validateStringNotEmpty(componentInstance.getCustomizationUUID())) {
- generateCustomizationUUID(componentInstance);
- }
- try {
-
- Either<ComponentInstance, TitanOperationStatus> addRes = addComponentInstanceToContainerComponent(containerComponentId, containerNodeType, instanceNumber, isCreateLocgicalName, componentInstance, compInstNodeType, allowDeleted);
- if (addRes.isRight()) {
- TitanOperationStatus status = addRes.right().value();
- log.error("Failed to add resource instance {} to service {}. status is {}", componentInstance, containerComponentId, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- ComponentInstance value = addRes.left().value();
- result = Either.left(value);
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- commitOrRollback(result);
- }
- }
- }
-
- private Either<TitanVertex, StorageOperationStatus> createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, boolean isCreateLocgicalName, ComponentInstance componentInstance,
- NodeTypeEnum compInstNodeType, boolean allowDeleted, boolean inTransaction, TitanVertex metadataVertex) {
- Either<TitanVertex, StorageOperationStatus> result = null;
-
- try {
-
- Either<TitanVertex, TitanOperationStatus> addRes = addComponentInstanceToContainerComponent(containerComponentId, containerNodeType, instanceNumber, isCreateLocgicalName, componentInstance, compInstNodeType, allowDeleted, metadataVertex);
- if (addRes.isRight()) {
- TitanOperationStatus status = addRes.right().value();
- log.error("Failed to add resource instance {} to service {}. status is {}", componentInstance, containerComponentId, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- TitanVertex value = addRes.left().value();
- result = Either.left(value);
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- commitOrRollback(result);
- }
- }
- }
-
- @Override
- public Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance, NodeTypeEnum instNodeType) {
-
- return createComponentInstance(containerComponentId, containerNodeType, instanceNumber, componentInstance, instNodeType, false);
-
- }
-
- @Override
- public Either<ComponentInstance, StorageOperationStatus> deleteComponentInstance(NodeTypeEnum containerNodeType, String containerComponentId, String resourceInstUid, boolean inTransaction) {
-
- Either<ComponentInstance, StorageOperationStatus> result = null;
-
- try {
-
- Either<ComponentInstance, TitanOperationStatus> deleteRes = removeComponentInstanceFromComponent(containerNodeType, containerComponentId, resourceInstUid);
-
- if (deleteRes.isRight()) {
- TitanOperationStatus status = deleteRes.right().value();
- log.error("Failed to remove resource instance {} from component {}. status is {}", resourceInstUid, containerComponentId, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- ComponentInstance value = deleteRes.left().value();
- result = Either.left(value);
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- commitOrRollback(result);
- }
- }
-
- }
-
- @Override
- public Either<ComponentInstance, StorageOperationStatus> deleteComponentInstance(NodeTypeEnum containerNodeType, String containerComponentId, String resourceInstUid) {
-
- return deleteComponentInstance(containerNodeType, containerComponentId, resourceInstUid, false);
- }
-
- private <T> void commitOrRollback(Either<T, StorageOperationStatus> result) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
-
- @Override
- public Either<Boolean, StorageOperationStatus> validateParent(String parentId, String uniqId, boolean inTransaction) {
-
- Either<Boolean, StorageOperationStatus> result = null;
- Either<Boolean, TitanOperationStatus> updateRes = validateParentonGraph(parentId, uniqId, inTransaction);
-
- if (updateRes.isRight()) {
- TitanOperationStatus status = updateRes.right().value();
- log.error("Failed to find resource instance name {}. status is {}", uniqId, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- Boolean value = updateRes.left().value();
-
- result = Either.left(value);
-
- return result;
-
- }
-
- public Either<Boolean, TitanOperationStatus> validateParentonGraph(String parentId, String uniqId, boolean inTransaction) {
-
- Either<TitanGraph, TitanOperationStatus> graphRes = titanGenericDao.getGraph();
- if (graphRes.isRight()) {
- log.debug("Failed to retrieve graph. status is {}", graphRes);
- return Either.right(graphRes.right().value());
- }
- TitanGraph titanGraph = graphRes.left().value();
- try {
- Iterable<TitanVertex> vertices = titanGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), uniqId).vertices();
- if (vertices == null || false == vertices.iterator().hasNext()) {
- return Either.right(TitanOperationStatus.INVALID_ID);
- }
-
- TitanVertex vertex = vertices.iterator().next();
-
- TitanVertexQuery query = vertex.query();
- query = query.labels(GraphEdgeLabels.RESOURCE_INST.getProperty()).direction(Direction.IN);
- Iterable<Vertex> verts = query.vertices();
- if (verts == null) {
- log.debug("No edges in graph for criteria");
- return Either.right(TitanOperationStatus.INVALID_ID);
- }
- Iterator<Vertex> vIter = verts.iterator();
- if (vIter.hasNext()) {
- Vertex vert = vIter.next();
- // vert.getProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- String resInstName = vert.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- if (resInstName.equals(parentId))
- return Either.left(Boolean.TRUE);
- }
- return Either.left(Boolean.FALSE);
- } finally {
- if (false == inTransaction) {
- titanGraph.tx().commit();
- }
- }
- }
-
- public Either<ComponentInstance, TitanOperationStatus> addComponentInstanceToContainerComponent(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, boolean isCreateLogicaName, ComponentInstance componentInstance,
- NodeTypeEnum compInstNodeType, boolean allowDeleted) {
- log.debug("Going to create component instance {} in component {}", componentInstance, containerComponentId);
-
- Either<TitanVertex, TitanOperationStatus> metadataVertex = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), containerComponentId);
- if (metadataVertex.isRight()) {
- TitanOperationStatus status = metadataVertex.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
- Either<TitanVertex, TitanOperationStatus> addComponentInstanceToContainerComponent = addComponentInstanceToContainerComponent(containerComponentId, containerNodeType, instanceNumber, isCreateLogicaName, componentInstance, compInstNodeType,
- allowDeleted, metadataVertex.left().value());
-
- if (addComponentInstanceToContainerComponent.isRight()) {
- TitanOperationStatus status = addComponentInstanceToContainerComponent.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
- TitanVertex ciVertex = addComponentInstanceToContainerComponent.left().value();
- Map<String, Object> properties = titanGenericDao.getProperties(ciVertex);
- ComponentInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.ResourceInstance.getName(), GraphElementTypeEnum.Node, properties, ComponentInstanceData.class);
-
- Either<ComponentInstance, TitanOperationStatus> createdResourceInstanceRes = createGroupInstancesOnComponentInstance(componentInstance, ciVertex, createdComponentInstance);
- return createdResourceInstanceRes;
- }
-
-
- public Either<ComponentInstance, TitanOperationStatus> createGroupInstancesOnComponentInstance(ComponentInstance componentInstance, TitanVertex ciVertex, ComponentInstanceData createdComponentInstance) {
- ComponentInstance createdResourceInstance = new ComponentInstance(createdComponentInstance.getComponentInstDataDefinition());
- createdResourceInstance.setGroupInstances(componentInstance.getGroupInstances());
- List<GroupInstance> groupInstancesList = new ArrayList<GroupInstance>();
- List<GroupDefinition> group = null;
- Either<List<GroupDefinition>, TitanOperationStatus> groupEither = groupOperation.getAllGroupsFromGraph(createdResourceInstance.getComponentUid(), NodeTypeEnum.Resource);
- if (groupEither.isRight() && groupEither.right().value() != TitanOperationStatus.OK && groupEither.right().value() != TitanOperationStatus.NOT_FOUND) {
- TitanOperationStatus status = groupEither.right().value();
- log.debug("Failed to associate group instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status);
- return Either.right(status);
- } else {
- if (groupEither.isLeft()) {
- group = groupEither.left().value();
- if (group != null && !group.isEmpty()) {
- List<GroupDefinition> vfGroupsList = group.stream().filter(p -> p.getType().equals("org.openecomp.groups.VfModule")).collect(Collectors.toList());
- for (GroupDefinition groupDefinition : vfGroupsList) {
- Either<GroupInstance, StorageOperationStatus> status = createGroupInstance(ciVertex, groupDefinition, createdResourceInstance);
- if (status.isRight()) {
- log.debug("Failed to associate group instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status);
-
- } else {
- GroupInstance groupInstance = status.left().value();
- groupInstancesList.add(groupInstance);
- }
-
- }
- createdResourceInstance.setGroupInstances(groupInstancesList);
- }
- }
-
- }
- return Either.left(createdResourceInstance);
- }
-
- public void generateCustomizationUUID(ComponentInstance componentInstance) {
- UUID uuid = UUID.randomUUID();
- componentInstance.setCustomizationUUID(uuid.toString());
- }
-
- /**
- *
- * @param containerComponentId
- * @param containerNodeType
- * @param instanceNumber
- * @param isCreateLogicaName
- * @param componentInstance
- * @param compInstNodeType
- * @param allowDeleted
- * @param metadataVertex
- * @return
- */
- public Either<TitanVertex, TitanOperationStatus> addComponentInstanceToContainerComponent(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, boolean isCreateLogicaName, ComponentInstance componentInstance,
- NodeTypeEnum compInstNodeType, boolean allowDeleted, TitanVertex metadataVertex) {
- TitanOperationStatus status;
- log.debug("Going to create component instance {} in component {}", componentInstance, containerComponentId);
- String instOriginComponentId = componentInstance.getComponentUid();
- String logicalName = componentInstance.getName();
- if (isCreateLogicaName)
- logicalName = createComponentInstLogicalName(instanceNumber, componentInstance.getName());
-
- ComponentInstanceData componentInstanceData = buildComponentInstanceData(componentInstance, containerComponentId, logicalName);
- Either<TitanVertex, TitanOperationStatus> originVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), instOriginComponentId);
- if (originVertexEither.isRight()) {
- log.debug("Failed to fetch vertex of origin resource for id {} error {}", instOriginComponentId, originVertexEither.right().value());
- return Either.right(originVertexEither.right().value());
- }
- TitanVertex originVertex = originVertexEither.left().value();
-
- Boolean isDeleted = (Boolean) titanGenericDao.getProperty(metadataVertex, GraphPropertiesDictionary.IS_DELETED.getProperty());
-
- if (!allowDeleted && (isDeleted != null) && (isDeleted == true)) {
- log.debug("Component {} is already deleted. Cannot add component instance", instOriginComponentId);
- return Either.right(TitanOperationStatus.INVALID_ID);
- }
- String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty());
- String resourceType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty());
-
- log.trace("Before adding component instance to graph. componentInstanceData = {}", componentInstanceData);
-
- Either<TitanVertex, TitanOperationStatus> createCIResult = titanGenericDao.createNode(componentInstanceData);
-
- log.debug("After adding component instance to graph. status is = {}", createCIResult);
-
- if (createCIResult.isRight()) {
- status = createCIResult.right().value();
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
- log.debug("Failed to create component instance node in graph. status is {}", status);
- return Either.right(status);
- }
- TitanVertex createdComponentInstanceVertex = createCIResult.left().value();
- TitanOperationStatus associateContainerRes = associateContainerCompToComponentInstance(metadataVertex, createdComponentInstanceVertex, logicalName);
-
- String componentInstanceUniqueId = componentInstanceData.getUniqueId();
- if (associateContainerRes != TitanOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
- log.debug("Failed to associate container component {} to component instance {}. Status is {}", containerComponentId, componentInstanceUniqueId, associateContainerRes);
- return Either.right(associateContainerRes);
- }
- String originId = (String) titanGenericDao.getProperty(createdComponentInstanceVertex, GraphPropertiesDictionary.TYPE.getProperty());
-
- TitanOperationStatus associateToInstOriginComponent = associateToInstOriginComponent(createdComponentInstanceVertex, originVertex, originId);
- if (associateToInstOriginComponent != TitanOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
- log.debug("Failed to associate component instance {} to its origin component {}. Status is {}", componentInstanceUniqueId, componentInstanceData.getComponentInstDataDefinition().getComponentUid(), associateToInstOriginComponent);
- return Either.right(associateToInstOriginComponent);
- }
-
- TitanOperationStatus associateCompInstToRequirements = associateCompInstToRequirements(createdComponentInstanceVertex, containerNodeType, compInstNodeType, originId);
- if (associateCompInstToRequirements != TitanOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
- log.debug("Failed to associate component instance {} to its origin requirements. Status is {}", componentInstanceUniqueId, associateCompInstToRequirements);
- return Either.right(associateCompInstToRequirements);
- }
- TitanOperationStatus associateCompInstToCapabilities = associateCompInstToCapabilities(createdComponentInstanceVertex, containerNodeType, compInstNodeType, originId);
- if (associateCompInstToCapabilities != TitanOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
- log.debug("Failed to associate component instance {} to its origin capabilities. Status is {}", componentInstanceUniqueId, associateCompInstToCapabilities);
- return Either.right(associateCompInstToCapabilities);
- }
- // Capability instance with property values implementation
- Either<List<ImmutablePair<TitanVertex, GraphEdge>>, TitanOperationStatus> cloneCapabilityInstancesRes = null;
- Either<List<GraphRelation>, TitanOperationStatus> associateComponentInstanceToCapabilityInstancesRes;
- status = null;
- if (!isCreateLogicaName) {
- // in case of cloning of component instance
- log.debug("Before cloning of capability instances of component instance {}.", componentInstance.getUniqueId());
- cloneCapabilityInstancesRes = cloneCapabilityInstancesOfResourceInstance(createdComponentInstanceVertex, componentInstance);
- if (cloneCapabilityInstancesRes.isRight() && !cloneCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- status = cloneCapabilityInstancesRes.right().value();
- log.debug("Failed to clone capability instances of component instance {}. Status is {}", componentInstance.getUniqueId(), status);
- }
- log.trace("After cloning of capability instances of component instance {}. Status is {}", componentInstance.getUniqueId(), status);
- } else if (containerNodeType.equals(NodeTypeEnum.Resource) && componentInstance.getCapabilities() != null && !componentInstance.getCapabilities().isEmpty()) {
- // in case of creation from scar
- TitanOperationStatus addPropertiesRes = createCapabilityInstancesWithPropertyValues(createdComponentInstanceVertex, componentInstanceUniqueId, componentInstance.getCapabilities(), true);
- if (addPropertiesRes != TitanOperationStatus.OK) {
- status = addPropertiesRes;
- log.debug("Failed to create capability instances with property values for component instance {}. Status is {}", componentInstance.getUniqueId(), status);
- }
- }
- if (status == null && containerNodeType.equals(NodeTypeEnum.Service)) {
- Map<String, Object> properties = titanGenericDao.getProperties(createdComponentInstanceVertex);
- ComponentInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.ResourceInstance.getName(), GraphElementTypeEnum.Node, properties, ComponentInstanceData.class);
- if (cloneCapabilityInstancesRes == null || cloneCapabilityInstancesRes.isRight()) {
- // in case of creating of service
- log.trace("Before associating component instance {} to capability instances .", componentInstance.getUniqueId());
- associateComponentInstanceToCapabilityInstancesRes = associateComponentInstanceToCapabilityInstancesOfResourceInstance(componentInstance);
- if (associateComponentInstanceToCapabilityInstancesRes.isRight() && !associateComponentInstanceToCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- status = associateComponentInstanceToCapabilityInstancesRes.right().value();
- log.debug("Failed to associate capability instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status);
- }
- log.trace("After associating component instance {} to capability instances . Status is {}", componentInstance.getUniqueId(), status);
- } else {
- // in case of cloning of service
- log.trace("Before associating created component instance {} to cloned capability instances.", componentInstanceUniqueId);
- TitanOperationStatus associationStatus = associateCreatedComponentInstanceToClonedCapabilityInstances(createdComponentInstanceVertex, componentInstanceUniqueId, cloneCapabilityInstancesRes.left().value());
- if (associationStatus != TitanOperationStatus.OK && associationStatus != TitanOperationStatus.NOT_FOUND) {
- status = associationStatus;
- log.debug("Failed to associate capability instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status);
- }
- log.trace("After associating created component instance {} to cloned capability instances. Status is {}", componentInstanceUniqueId, status);
- }
- }
-
- if (status == null) {
- // ComponentInstance createdResourceInstance = new
- // ComponentInstance(createdComponentInstance.getComponentInstDataDefinition());
- //
- // String icon = (String) titanGenericDao.getProperty(originVertex,
- // GraphPropertiesDictionary.ICON.getProperty());
- // createdResourceInstance.setIcon(icon);
- return Either.left(createdComponentInstanceVertex);
- }
- return Either.right(status);
- }
-
- private Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> createCapabilityInstancesWithPropertyValues(String resourceInstanceId, Map<String, List<CapabilityDefinition>> capabilities,
- boolean isNewlyCreatedResourceInstance) {
- TitanOperationStatus error;
- Map<CapabilityInstData, List<PropertyValueData>> result = new HashMap<>();
- for (Entry<String, List<CapabilityDefinition>> capailityEntry : capabilities.entrySet()) {
- CapabilityDefinition capability = capailityEntry.getValue().get(0);
- if (capability.getProperties() != null && !capability.getProperties().isEmpty()) {
- Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> addPropertiesRes = addCapabilityPropertyValuesToResourceInstance(resourceInstanceId, capability, isNewlyCreatedResourceInstance);
- if (addPropertiesRes.isRight()) {
- error = addPropertiesRes.right().value();
- log.debug("Failed to add property values to capabilities of component instance {}. Status is {}", resourceInstanceId, error);
- return Either.right(error);
- } else {
- result.putAll(addPropertiesRes.left().value());
- }
- }
- }
- return Either.left(result);
- }
-
- private TitanOperationStatus createCapabilityInstancesWithPropertyValues(TitanVertex resourceInstanceVertex, String resourceInstanceId, Map<String, List<CapabilityDefinition>> capabilities, boolean isNewlyCreatedResourceInstance) {
- TitanOperationStatus result = TitanOperationStatus.OK;
-
- for (Entry<String, List<CapabilityDefinition>> capailityEntry : capabilities.entrySet()) {
- CapabilityDefinition capability = capailityEntry.getValue().get(0);
- if (capability.getProperties() != null && !capability.getProperties().isEmpty()) {
- TitanOperationStatus addPropertiesRes = addCapabilityPropertyValuesToResourceInstance(resourceInstanceVertex, resourceInstanceId, capability, isNewlyCreatedResourceInstance);
- if (addPropertiesRes != TitanOperationStatus.OK) {
- result = addPropertiesRes;
- log.debug("Failed to add property values to capabilities of component instance {}. Status is {}", resourceInstanceId, result);
- return result;
- }
- }
- }
- return result;
- }
-
- private Either<List<GraphRelation>, TitanOperationStatus> associateCreatedComponentInstanceToClonedCapabilityInstances(String newComponentResourceId, List<ImmutablePair<CapabilityInstData, GraphEdge>> capabilityInstances) {
- TitanOperationStatus error = null;
- List<GraphRelation> relationsToCapabilityInstances = new ArrayList<>();
- UniqueIdData componentInstanceIdData = new UniqueIdData(NodeTypeEnum.ResourceInstance, newComponentResourceId);
- for (ImmutablePair<CapabilityInstData, GraphEdge> capInstPair : capabilityInstances) {
- Either<GraphRelation, TitanOperationStatus> associateComponentInstanceToCapabilityinstanceRes = titanGenericDao.createRelation(componentInstanceIdData, capInstPair.getLeft(), GraphEdgeLabels.CAPABILITY_INST,
- capInstPair.getRight().getProperties());
- if (associateComponentInstanceToCapabilityinstanceRes.isRight()) {
- error = associateComponentInstanceToCapabilityinstanceRes.right().value();
- log.debug("Failed to associate capability instance {} to resource instance {} status is {}.", capInstPair.getLeft().getUniqueId(), newComponentResourceId, error);
- break;
- } else {
- relationsToCapabilityInstances.add(associateComponentInstanceToCapabilityinstanceRes.left().value());
- }
- }
- if (error == null) {
- return Either.left(relationsToCapabilityInstances);
- }
- return Either.right(error);
- }
-
- private TitanOperationStatus associateCreatedComponentInstanceToClonedCapabilityInstances(TitanVertex riVertex, String newComponentResourceId, List<ImmutablePair<TitanVertex, GraphEdge>> capabilityInstances) {
- TitanOperationStatus error = null;
- for (ImmutablePair<TitanVertex, GraphEdge> capInstPair : capabilityInstances) {
- TitanOperationStatus associateComponentInstanceToCapabilityinstanceRes = titanGenericDao.createEdge(riVertex, capInstPair.getLeft(), GraphEdgeLabels.CAPABILITY_INST, capInstPair.getRight().getProperties());
- if (associateComponentInstanceToCapabilityinstanceRes != TitanOperationStatus.OK) {
- error = associateComponentInstanceToCapabilityinstanceRes;
- log.debug("Failed to associate capability instance {} to resource instance {} status is {} .", capInstPair.getLeft(), newComponentResourceId, error);
- break;
- }
- }
- if (error == null) {
- return TitanOperationStatus.OK;
- }
- return error;
- }
-
- private Either<List<GraphRelation>, TitanOperationStatus> associateComponentInstanceToCapabilityInstancesOfResourceInstance(ComponentInstance componentInstance) {
- TitanOperationStatus error = null;
- String resourceId = componentInstance.getComponentUid();
- String componentResourceId = componentInstance.getUniqueId();
- UniqueIdData componentInstanceIdData = new UniqueIdData(NodeTypeEnum.ResourceInstance, componentResourceId);
- List<ImmutablePair<ComponentInstanceData, GraphEdge>> resourceInstancesPair;
- List<ImmutablePair<CapabilityInstData, GraphEdge>> allCapabilityInstancesList = new ArrayList<>();
- List<GraphRelation> relationsToCapabilityInstances = new ArrayList<>();
- Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> getAllResourceInstanceRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId,
- GraphEdgeLabels.RESOURCE_INST, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
- if (getAllResourceInstanceRes.isRight() && !getAllResourceInstanceRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- error = getAllResourceInstanceRes.right().value();
- log.debug("Failed to retrieve resource instances from resource {} status is {}.", resourceId, error);
- }
- if (getAllResourceInstanceRes.isLeft()) {
- resourceInstancesPair = getAllResourceInstanceRes.left().value();
- ComponentInstanceData ri;
- for (ImmutablePair<ComponentInstanceData, GraphEdge> riPair : resourceInstancesPair) {
- ri = riPair.getLeft();
- Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), ri.getUniqueId(),
- GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class);
- if (getCapabilityInstancesRes.isRight() && !getCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- error = getCapabilityInstancesRes.right().value();
- log.debug("Failed to retrieve capability instances of resource instance {} status is {}.", ri.getUniqueId(), error);
- break;
- }
- if (getCapabilityInstancesRes.isLeft()) {
- allCapabilityInstancesList.addAll(getCapabilityInstancesRes.left().value());
- }
- }
- }
- if (error == null && !allCapabilityInstancesList.isEmpty()) {
- for (ImmutablePair<CapabilityInstData, GraphEdge> capInstPair : allCapabilityInstancesList) {
- Either<GraphRelation, TitanOperationStatus> associateComponentInstanceToCapabilityinstanceRes = titanGenericDao.createRelation(componentInstanceIdData, capInstPair.getLeft(), GraphEdgeLabels.CAPABILITY_INST,
- capInstPair.getRight().getProperties());
- if (associateComponentInstanceToCapabilityinstanceRes.isRight()) {
- error = associateComponentInstanceToCapabilityinstanceRes.right().value();
- log.debug("Failed to associate capability instance {} to resource instance {} status is {}.", capInstPair.getLeft().getUniqueId(), componentResourceId, error);
- break;
- } else {
- relationsToCapabilityInstances.add(associateComponentInstanceToCapabilityinstanceRes.left().value());
- }
- }
- }
- if (error == null) {
- return Either.left(relationsToCapabilityInstances);
- }
- return Either.right(error);
- }
-
- private NodeTypeEnum detectOriginType(String label, ComponentInstanceData componentInstanceData, String resourceTypeStr) {
- NodeTypeEnum res = null;
- res = NodeTypeEnum.getByName(label);
- switch (res) {
- case Service:
- componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.SERVICE);
- break;
- case Product:
- componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.PRODUCT);
- break;
- case Resource:
- ResourceTypeEnum resourceType = ResourceTypeEnum.valueOf(resourceTypeStr);
- switch (resourceType) {
- case VF:
- componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VF);
- break;
- case VFC:
- componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VFC);
- break;
- case VFCMT:
- componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VFCMT);
- break;
- case CP:
- componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.CP);
- break;
- case VL:
- componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VL);
- break;
- case CVFC:
- componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.CVFC);
- break;
- case PNF:
- componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.PNF);
- break;
-
- }
- break;
- default:
- break;
- }
- return res;
- }
-
- private Either<GraphRelation, TitanOperationStatus> associateToInstOriginComponent(ComponentInstanceData componentInstanceData, NodeTypeEnum compInstNodeType) {
-
- UniqueIdData resourceIdData = new UniqueIdData(compInstNodeType, componentInstanceData.getComponentInstDataDefinition().getComponentUid());
-
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(componentInstanceData, resourceIdData, GraphEdgeLabels.INSTANCE_OF, null);
-
- log.debug("After associating resource instance {} to resource {}. status is {}", componentInstanceData.getUniqueId(), componentInstanceData.getComponentInstDataDefinition().getUniqueId(), createRelation);
-
- return createRelation;
- }
-
- private TitanOperationStatus associateToInstOriginComponent(TitanVertex componentInstanceVertex, TitanVertex originVertex, String originId) {
-
- TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, originVertex, GraphEdgeLabels.INSTANCE_OF, null);
-
- log.debug("After associating resource instance {} to resource {}. status is {}", componentInstanceVertex, originId, createRelation);
-
- return createRelation;
- }
-
- private Either<List<GraphRelation>, TitanOperationStatus> associateCompInstToRequirements(ComponentInstanceData componentInstanceData, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType) {
- log.trace("Starting to copy origin component requirements to its component instance");
- String compInstOriginId = componentInstanceData.getComponentInstDataDefinition().getComponentUid();
- List<GraphRelation> graphRelations = new ArrayList<>();
-
- // case of VFC / CP / VL
- if (compInstNodeType.equals(NodeTypeEnum.Resource)) {
- createRequirementRelationsFromAtomicResource(componentInstanceData, compInstOriginId, graphRelations);
-
- }
- // case of VF / Service / Product
- createCalculatedRequirementRelationsFromComponent(componentInstanceData, containerNodeType, compInstNodeType, graphRelations, compInstOriginId);
-
- log.trace("Finished to copy origin component requirements to its component instance, created {} new calculated requirement relations", graphRelations.size());
- return Either.left(graphRelations);
- }
-
- private TitanOperationStatus associateCompInstToRequirements(TitanVertex componentInstanceVertex, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, String originId) {
- log.trace("Starting to copy origin component requirements to its component instance");
- TitanOperationStatus status = TitanOperationStatus.OK;
- // case of VFC / CP / VL
- if (compInstNodeType.equals(NodeTypeEnum.Resource)) {
- status = createRequirementRelationsFromAtomicResource(componentInstanceVertex, originId);
- if (!status.equals(TitanOperationStatus.OK)) {
- log.debug("Failed create relation to requirement of origin {} error {}", originId, status);
- return status;
- }
- }
- // case of VF / Service / Product
- status = createCalculatedRequirementRelationsFromComponent(componentInstanceVertex, containerNodeType, compInstNodeType, originId);
-
- log.trace("Finished to copy origin component requirements to its component instance with status {}", status);
- return status;
- }
-
- private void createRequirementRelationsFromAtomicResource(ComponentInstanceData componentInstanceData, String compInstOriginId, List<GraphRelation> graphRelations) {
- Map<String, RequirementDefinition> requirements = new HashMap<String, RequirementDefinition>();
- Set<String> caseInsensitiveReqNames = new HashSet<>();
-
- TitanOperationStatus status = requirementOperation.findAllRequirementsRecursively(compInstOriginId, requirements, caseInsensitiveReqNames);
- if (status != TitanOperationStatus.OK) {
- log.debug("Couldn't fetch requirements of component {}, error: {}", compInstOriginId, status);
- }
-
- log.trace("Found {} requirements for component {}, ", requirements.size(), compInstOriginId);
- for (Entry<String, RequirementDefinition> reqPair : requirements.entrySet()) {
- RequirementDefinition requirementDef = reqPair.getValue();
- RequirementData requirementData = new RequirementData();
- requirementData.setUniqueId(requirementDef.getUniqueId());
-
- log.trace("Creating calculated requirement relation from component instance {} to requirement {}", componentInstanceData.getUniqueId(), requirementDef.getUniqueId());
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), reqPair.getKey());
-
- props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), componentInstanceData.getUniqueId());
- if (requirementDef.getMinOccurrences() == null) {
- props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), RequirementDataDefinition.MIN_OCCURRENCES);
- } else {
- props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requirementDef.getMinOccurrences());
- }
- if (requirementDef.getMaxOccurrences() == null) {
- props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES);
- } else {
- props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), requirementDef.getMaxOccurrences());
- }
-
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(componentInstanceData, requirementData, GraphEdgeLabels.CALCULATED_REQUIREMENT, props);
- if (createRelation.isRight()) {
- TitanOperationStatus titanOperationStatus = createRelation.right().value();
- log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", componentInstanceData.getUniqueId(), requirementDef.getUniqueId(), titanOperationStatus);
- }
- graphRelations.add(createRelation.left().value());
- }
- }
-
- private TitanOperationStatus createRequirementRelationsFromAtomicResource(TitanVertex componentInstanceVertex, String compInstOriginId) {
- Map<String, RequirementDefinition> requirements = new HashMap<String, RequirementDefinition>();
- Set<String> caseInsensitiveReqNames = new HashSet<>();
-
- TitanOperationStatus status = requirementOperation.findAllRequirementsRecursively(compInstOriginId, requirements, caseInsensitiveReqNames);
- if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) {
- log.debug("Couldn't fetch requirements of component {}, error: {}", compInstOriginId, status);
- return status;
- }
-
- String compoInstId = (String) titanGenericDao.getProperty(componentInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- log.trace("Found {} requirements for component {}, ", requirements.size(), compInstOriginId);
- for (Entry<String, RequirementDefinition> reqPair : requirements.entrySet()) {
- RequirementDefinition requirementDef = reqPair.getValue();
- RequirementData requirementData = new RequirementData();
- requirementData.setUniqueId(requirementDef.getUniqueId());
-
- log.trace("Creating calculated requirement relation from component instance {} to requirement {}", compoInstId, requirementDef.getUniqueId());
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), reqPair.getKey());
-
- props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), compoInstId);
- if (requirementDef.getMinOccurrences() == null) {
- props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), RequirementDataDefinition.MIN_OCCURRENCES);
- } else {
- props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requirementDef.getMinOccurrences());
- }
- if (requirementDef.getMaxOccurrences() == null) {
- props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES);
- } else {
- props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), requirementDef.getMaxOccurrences());
- }
-
- TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, requirementData, GraphEdgeLabels.CALCULATED_REQUIREMENT, props);
- if (!createRelation.equals(TitanOperationStatus.OK)) {
- log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", compoInstId, requirementDef.getUniqueId(), createRelation);
- return createRelation;
- }
- }
- return TitanOperationStatus.OK;
- }
-
- private Either<List<GraphRelation>, TitanOperationStatus> associateCompInstToCapabilities(ComponentInstanceData componentInstanceData, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType) {
-
- log.trace("Starting to copy origin component capabilities to its component instance");
- List<GraphRelation> graphRelations = new ArrayList<>();
-
- String compInstOriginId = componentInstanceData.getComponentInstDataDefinition().getComponentUid();
-
- // case of VFC / CP / VL
- if (compInstNodeType.equals(NodeTypeEnum.Resource)) {
- createCaculatedRelationsFromAtomicResource(componentInstanceData, graphRelations, compInstOriginId);
- }
-
- // case of VF / Service / Product
- createCalculatedCapabilityRelationsFromComponent(componentInstanceData, containerNodeType, compInstNodeType, graphRelations, compInstOriginId);
-
- log.trace("Finished to copy origin component capabilities to its component instance, created {} new calculated capability relations", graphRelations.size());
- return Either.left(graphRelations);
- }
-
- private TitanOperationStatus associateCompInstToCapabilities(TitanVertex componentInstanceVertex, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, String originId) {
-
- log.trace("Starting to copy origin component capabilities to its component instance");
- TitanOperationStatus status = TitanOperationStatus.OK;
-
- // case of VFC / CP / VL
- if (compInstNodeType.equals(NodeTypeEnum.Resource)) {
- status = createCaculatedRelationsFromAtomicResource(componentInstanceVertex, originId);
- if (!status.equals(TitanOperationStatus.OK)) {
- return status;
- }
- }
-
- // case of VF / Service / Product
- status = createCalculatedCapabilityRelationsFromComponent(componentInstanceVertex, containerNodeType, compInstNodeType, originId);
-
- return status;
- }
-
- private void createCalculatedRequirementRelationsFromComponent(ComponentInstanceData componentInstanceData, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, List<GraphRelation> graphRelations, String compInstOriginId) {
-
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> componentInstancesOfComponent = getComponentInstancesOfComponent(compInstOriginId, containerNodeType, compInstNodeType);
- if (componentInstancesOfComponent.isLeft() && !componentInstancesOfComponent.left().value().left.isEmpty()) {
- List<ComponentInstance> componentInstances = componentInstancesOfComponent.left().value().left;
- for (ComponentInstance componentInstance : componentInstances) {
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(containerNodeType), componentInstance.getUniqueId(),
- GraphEdgeLabels.CALCULATED_REQUIREMENT, NodeTypeEnum.Requirement, RequirementData.class);
-
- if (childrenNodes.isLeft() && !childrenNodes.left().value().isEmpty()) {
- List<ImmutablePair<RequirementData, GraphEdge>> list = childrenNodes.left().value();
- for (ImmutablePair<RequirementData, GraphEdge> calculatedReq : list) {
-
- GraphEdge edge = calculatedReq.right;
- Map<String, Object> properties = edge.getProperties();
- String source = null;
- String occurrences = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES;
- String minOccurrences = RequirementDataDefinition.MIN_OCCURRENCES;
-
- if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) {
- source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty());
- }
- if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty())) {
- occurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
- }
- if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) {
- minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
- }
-
- String capabilityName = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty());
- Either<GraphRelation, TitanOperationStatus> createRelation = createCalculatedRequirementEdge(componentInstanceData, source, capabilityName, calculatedReq.left, componentInstance, occurrences, minOccurrences);
- if (createRelation.isLeft()) {
- graphRelations.add(createRelation.left().value());
- }
- }
- }
- }
- }
- }
-
- private TitanOperationStatus createCalculatedRequirementRelationsFromComponent(TitanVertex componentInstanceVertex, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, String compInstOriginId) {
-
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> componentInstancesOfComponent = getComponentInstancesOfComponent(compInstOriginId, containerNodeType, compInstNodeType);
- if (componentInstancesOfComponent.isLeft() && !componentInstancesOfComponent.left().value().left.isEmpty()) {
- List<ComponentInstance> componentInstances = componentInstancesOfComponent.left().value().left;
- for (ComponentInstance componentInstance : componentInstances) {
-
- Either<List<ImmutablePair<TitanVertex, Edge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(containerNodeType), componentInstance.getUniqueId(),
- GraphEdgeLabels.CALCULATED_REQUIREMENT);
-
- if (childrenNodes.isLeft() && !childrenNodes.left().value().isEmpty()) {
- List<ImmutablePair<TitanVertex, Edge>> list = childrenNodes.left().value();
- for (ImmutablePair<TitanVertex, Edge> calculatedReq : list) {
-
- Edge edge = calculatedReq.right;
- Map<String, Object> properties = titanGenericDao.getProperties(edge);
- String source = null;
- String occurrences = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES;
- String minOccurrences = RequirementDataDefinition.MIN_OCCURRENCES;
-
- if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) {
- source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty());
- }
- if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty())) {
- occurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
- }
- if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) {
- minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
- }
-
- String capabilityName = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty());
- TitanOperationStatus createRelation = createCalculatedRequirementEdge(componentInstanceVertex, source, capabilityName, calculatedReq.left, componentInstance, occurrences, minOccurrences);
- if (!createRelation.equals(TitanOperationStatus.OK)) {
- log.debug("Failed to create calculated requirement edge, status ", createRelation);
- return createRelation;
- }
- }
- }
- }
- }
- return TitanOperationStatus.OK;
- }
-
- private void createCalculatedCapabilityRelationsFromComponent(ComponentInstanceData componentInstanceData, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, List<GraphRelation> graphRelations, String compInstOriginId) {
-
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> componentInstancesOfComponent = getComponentInstancesOfComponent(compInstOriginId, containerNodeType, compInstNodeType);
- if (componentInstancesOfComponent.isLeft() && !componentInstancesOfComponent.left().value().left.isEmpty()) {
- List<ComponentInstance> componentInstances = componentInstancesOfComponent.left().value().left;
- for (ComponentInstance componentInstance : componentInstances) {
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(compInstNodeType), componentInstance.getUniqueId(),
- GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class);
-
- if (childrenNodes.isLeft() && !childrenNodes.left().value().isEmpty()) {
- List<ImmutablePair<CapabilityData, GraphEdge>> list = childrenNodes.left().value();
- for (ImmutablePair<CapabilityData, GraphEdge> calculatedCap : list) {
-
- GraphEdge edge = calculatedCap.right;
- Map<String, Object> properties = edge.getProperties();
- String source = null;
- if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) {
- source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty());
- }
- String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
- String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES;
- if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) {
- minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
- }
- if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty())) {
- occurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
- }
-
- String capabilityName = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty());
- Either<GraphRelation, TitanOperationStatus> createRelation = createCalculatedCapabilityEdge(componentInstanceData, source, capabilityName, calculatedCap.left, componentInstance.getUniqueId(), minOccurrences, occurrences);
- if (createRelation.isLeft()) {
- graphRelations.add(createRelation.left().value());
- }
- }
- }
- }
- }
- }
-
- private TitanOperationStatus createCalculatedCapabilityRelationsFromComponent(TitanVertex componentInstanceVertex, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, String compInstOriginId) {
-
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> componentInstancesOfComponent = getComponentInstancesOfComponent(compInstOriginId, containerNodeType, compInstNodeType);
- if (componentInstancesOfComponent.isLeft() && !componentInstancesOfComponent.left().value().left.isEmpty()) {
- List<ComponentInstance> componentInstances = componentInstancesOfComponent.left().value().left;
- for (ComponentInstance componentInstance : componentInstances) {
- Either<List<ImmutablePair<TitanVertex, Edge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(compInstNodeType), componentInstance.getUniqueId(),
- GraphEdgeLabels.CALCULATED_CAPABILITY);
-
- if (childrenNodes.isLeft() && !childrenNodes.left().value().isEmpty()) {
- List<ImmutablePair<TitanVertex, Edge>> list = childrenNodes.left().value();
- for (ImmutablePair<TitanVertex, Edge> calculatedCap : list) {
-
- Edge edge = calculatedCap.right;
- Map<String, Object> properties = titanGenericDao.getProperties(edge);
- String source = null;
- if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) {
- source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty());
- }
- String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
- String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES;
- if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) {
- minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
- }
- if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty())) {
- occurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
- }
-
- String capabilityName = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty());
- TitanOperationStatus createRelation = createCalculatedCapabilityEdge(componentInstanceVertex, source, capabilityName, calculatedCap.left, componentInstance.getUniqueId(), minOccurrences, occurrences);
- if (!createRelation.equals(TitanOperationStatus.OK)) {
- return createRelation;
- }
- }
- }
- }
- }
- return TitanOperationStatus.OK;
- }
-
- private void createCaculatedRelationsFromAtomicResource(ComponentInstanceData componentInstanceData, List<GraphRelation> graphRelations, String compInstOriginId) {
-
- Map<String, CapabilityDefinition> capabilities = new HashMap<String, CapabilityDefinition>();
- Set<String> caseInsensitiveCapNames = new HashSet<>();
- TitanOperationStatus getAllCapabilities = capabilityOperation.getAllCapabilitiesRecusive(NodeTypeEnum.Resource, compInstOriginId, true, capabilities, caseInsensitiveCapNames, true);
-
- if (!getAllCapabilities.equals(TitanOperationStatus.OK)) {
- if (getAllCapabilities != TitanOperationStatus.NOT_FOUND) {
- log.debug("Couldn't fetch capabilities of component {}, error: {}", compInstOriginId, getAllCapabilities);
- return;
- }
- }
- log.trace("Found {} capabilities for component {}, ", capabilities.size(), compInstOriginId);
- for (Entry<String, CapabilityDefinition> capPair : capabilities.entrySet()) {
- CapabilityDefinition capabilityData = capPair.getValue();
- log.trace("Creating calculated capability relation from component instance {} to capability {}", componentInstanceData.getUniqueId(), capabilityData.getUniqueId());
- CapabilityData capabilityDataNode = new CapabilityData();
- capabilityDataNode.setUniqueId(capabilityData.getUniqueId());
- String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
- String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES;
- if (capabilityData.getMinOccurrences() != null) {
- minOccurrences = capabilityData.getMinOccurrences();
- }
- if (capabilityData.getMinOccurrences() != null) {
- occurrences = capabilityData.getMaxOccurrences();
- }
-
- Either<GraphRelation, TitanOperationStatus> createRelation = createCalculatedCapabilityEdge(componentInstanceData, compInstOriginId, capPair.getKey(), capabilityDataNode, componentInstanceData.getUniqueId(), minOccurrences, occurrences);
- graphRelations.add(createRelation.left().value());
- }
- }
-
- private TitanOperationStatus createCaculatedRelationsFromAtomicResource(TitanVertex componentInstanceVertex, String compInstOriginId) {
-
- Map<String, CapabilityDefinition> capabilities = new HashMap<String, CapabilityDefinition>();
- Set<String> caseInsensitiveCapNames = new HashSet<>();
- TitanOperationStatus getAllCapabilities = capabilityOperation.getAllCapabilitiesRecusive(NodeTypeEnum.Resource, compInstOriginId, true, capabilities, caseInsensitiveCapNames, true);
-
- if (!getAllCapabilities.equals(TitanOperationStatus.OK)) {
- if (getAllCapabilities != TitanOperationStatus.NOT_FOUND) {
- log.debug("Couldn't fetch capabilities of component {}, error: {}", compInstOriginId, getAllCapabilities);
- }
- }
- log.trace("Found {} capabilities for component {}, ", capabilities.size(), compInstOriginId);
- String compoInstId = (String) titanGenericDao.getProperty(componentInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
-
- for (Entry<String, CapabilityDefinition> capPair : capabilities.entrySet()) {
- CapabilityDefinition capabilityData = capPair.getValue();
- log.trace("Creating calculated capability relation from component instance {} to capability {}", compoInstId, capabilityData.getUniqueId());
- CapabilityData capabilityDataNode = new CapabilityData();
- capabilityDataNode.setUniqueId(capabilityData.getUniqueId());
- String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
- String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES;
- if (capabilityData.getMinOccurrences() != null) {
- minOccurrences = capabilityData.getMinOccurrences();
- }
- if (capabilityData.getMinOccurrences() != null) {
- occurrences = capabilityData.getMaxOccurrences();
- }
-
- TitanOperationStatus createRelation = createCalculatedCapabilityEdge(componentInstanceVertex, compInstOriginId, capPair.getKey(), capabilityDataNode, compoInstId, minOccurrences, occurrences);
- if (!createRelation.equals(TitanOperationStatus.OK)) {
- return createRelation;
- }
- }
- return TitanOperationStatus.OK;
- }
-
- private Either<GraphRelation, TitanOperationStatus> createCalculatedCapabilityEdge(ComponentInstanceData componentInstanceData, String compInstOriginId, String capabilityName, CapabilityData capabilityDataNode, String componentInstanceId,
- String minOccurrences, String occurrences) {
- Map<String, Object> props = prepareEdgeCapabiltyProperites(compInstOriginId, capabilityName, componentInstanceId, minOccurrences, occurrences);
-
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(componentInstanceData, capabilityDataNode, GraphEdgeLabels.CALCULATED_CAPABILITY, props);
- if (createRelation.isRight()) {
- TitanOperationStatus titanOperationStatus = createRelation.right().value();
- log.debug("Failed to create calculated capability from component instance {} to capability {}, error: {}", componentInstanceData.getUniqueId(), capabilityDataNode.getUniqueId(), titanOperationStatus);
- return Either.right(titanOperationStatus);
- }
- return createRelation;
- }
-
- private TitanOperationStatus createCalculatedCapabilityEdge(TitanVertex componentInstanceVertex, String compInstOriginId, String capabilityName, CapabilityData capabilityDataNode, String componentInstanceId, String minOccurrences,
- String occurrences) {
- Map<String, Object> props = prepareEdgeCapabiltyProperites(compInstOriginId, capabilityName, componentInstanceId, minOccurrences, occurrences);
-
- TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, capabilityDataNode, GraphEdgeLabels.CALCULATED_CAPABILITY, props);
- if (!createRelation.equals(TitanOperationStatus.OK)) {
- log.debug("Failed to create calculated capability from component instance {} to capability {}, error: {}", componentInstanceId, capabilityDataNode.getUniqueId(), createRelation);
- }
- return createRelation;
- }
-
- private TitanOperationStatus createCalculatedCapabilityEdge(TitanVertex componentInstanceVertex, String compInstOriginId, String capabilityName, TitanVertex capabilityDataVertex, String componentInstanceId, String minOccurrences,
- String occurrences) {
- Map<String, Object> props = prepareEdgeCapabiltyProperites(compInstOriginId, capabilityName, componentInstanceId, minOccurrences, occurrences);
-
- TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, capabilityDataVertex, GraphEdgeLabels.CALCULATED_CAPABILITY, props);
- if (!createRelation.equals(TitanOperationStatus.OK)) {
- log.debug("Failed to create calculated capability from component instance {} to capability {}, error: {}", componentInstanceId, capabilityName, createRelation);
- }
- return createRelation;
- }
-
- private Map<String, Object> prepareEdgeCapabiltyProperites(String compInstOriginId, String capabilityName, String componentInstanceId, String minOccurrences, String occurrences) {
- Map<String, Object> props = new HashMap<String, Object>();
- if (capabilityName != null)
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName);
- if (compInstOriginId != null)
- props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(), compInstOriginId);
- if (componentInstanceId != null) {
- props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), componentInstanceId);
- }
- props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), minOccurrences);
- props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), occurrences);
- return props;
- }
-
- private Either<GraphRelation, TitanOperationStatus> createCalculatedRequirementEdge(ComponentInstanceData componentInstanceData, String compInstOriginId, String capabilityName, RequirementData requirementData, ComponentInstance componentInstance,
- String occurrences, String minOccurrences) {
- Map<String, Object> props = new HashMap<String, Object>();
- if (capabilityName != null)
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName);
- if (compInstOriginId != null)
- props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(), compInstOriginId);
- if (componentInstance != null) {
- props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), componentInstance.getUniqueId());
- }
- props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), occurrences);
- props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), minOccurrences);
-
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(componentInstanceData, requirementData, GraphEdgeLabels.CALCULATED_REQUIREMENT, props);
- if (createRelation.isRight()) {
- TitanOperationStatus titanOperationStatus = createRelation.right().value();
- log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", componentInstanceData.getUniqueId(), requirementData.getUniqueId(), titanOperationStatus);
- return Either.right(titanOperationStatus);
- }
- return createRelation;
- }
-
- private TitanOperationStatus createCalculatedRequirementEdge(TitanVertex componentInstanceVertex, String compInstOriginId, String capabilityName, TitanVertex requirementVertex, ComponentInstance componentInstance, String occurrences,
- String minOccurrences) {
- Map<String, Object> props = new HashMap<String, Object>();
- if (capabilityName != null)
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName);
- if (compInstOriginId != null)
- props.put(GraphEdgePropertiesDictionary.SOURCE.getProperty(), compInstOriginId);
- if (componentInstance != null) {
- props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), componentInstance.getUniqueId());
- }
- props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), occurrences);
- props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), minOccurrences);
-
- TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstanceVertex, requirementVertex, GraphEdgeLabels.CALCULATED_REQUIREMENT, props);
- if (!createRelation.equals(TitanOperationStatus.OK)) {
- log.debug("Failed to create calculated requirement from component instance {} to requirement {}, error: {}", componentInstance.getUniqueId(), capabilityName, createRelation);
- return createRelation;
- }
- return createRelation;
- }
-
- /**
- * Make a relation between service to resource instance.
- *
- * @param containerCompIdData
- * @param componentInstanceData
- * @param logicalName
- * @return
- */
- private Either<GraphRelation, TitanOperationStatus> associateContainerCompToComponentInstance(UniqueIdData containerCompIdData, ComponentInstanceData componentInstanceData, String logicalName) {
- Map<String, Object> properties = new HashMap<String, Object>();
-
- properties.put(GraphPropertiesDictionary.NAME.getProperty(), logicalName);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(containerCompIdData, componentInstanceData, GraphEdgeLabels.RESOURCE_INST, properties);
-
- log.debug("After associating container component {} to resource instance {} with logical name {}. Status is {}", containerCompIdData.getUniqueId(), componentInstanceData.getUniqueId(), logicalName, createRelation);
-
- return createRelation;
- }
-
- private TitanOperationStatus associateContainerCompToComponentInstance(TitanVertex containerCompVertex, TitanVertex componentInstanceVertex, String logicalName) {
- Map<String, Object> properties = new HashMap<String, Object>();
-
- properties.put(GraphPropertiesDictionary.NAME.getProperty(), logicalName);
- TitanOperationStatus createRelation = titanGenericDao.createEdge(containerCompVertex, componentInstanceVertex, GraphEdgeLabels.RESOURCE_INST, properties);
-
- return createRelation;
- }
-
- @Override
- public String createComponentInstLogicalName(String instanceNumber, String componentInstanceName) {
-
- String logicalName = buildComponentInstanceLogicalName(instanceNumber, componentInstanceName);
-
- return logicalName;
- }
-
- private String buildComponentInstanceLogicalName(String instanceNumber, String lastToken) {
- return lastToken + " " + (instanceNumber == null ? 0 : instanceNumber);
- }
-
- private ComponentInstanceData buildComponentInstanceData(ComponentInstance resourceInstance, String componentId, String logicalName) {
-
- String ciOriginComponentUid = resourceInstance.getComponentUid();
-
- ComponentInstanceDataDefinition dataDefinition = new ComponentInstanceDataDefinition(resourceInstance);
-
- Long creationDate = resourceInstance.getCreationTime();
- if (creationDate == null) {
- creationDate = System.currentTimeMillis();
- }
- dataDefinition.setCreationTime(creationDate);
- dataDefinition.setModificationTime(creationDate);
- // dataDefinition.setResourceUid(resourceUid);
- // String replacmentlogicalName = logicalName.replaceAll(" ",
- // "_").toLowerCase();
- dataDefinition.setName(logicalName);
- if (dataDefinition.getNormalizedName() == null)
- dataDefinition.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(logicalName));
- dataDefinition.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentId, ciOriginComponentUid, dataDefinition.getNormalizedName()));
-
- ComponentInstanceData resourceInstanceData = new ComponentInstanceData(dataDefinition);
-
- return resourceInstanceData;
- }
-
- public Either<ComponentInstance, TitanOperationStatus> removeComponentInstanceFromComponent(NodeTypeEnum containerNodeType, String containerComponentId, String componentInstanceUid) {
-
- log.debug("Going to delete component instance {} under component {}", componentInstanceUid, containerComponentId);
-
- Either<ComponentInstanceData, TitanOperationStatus> node = findResourceInstance(componentInstanceUid);
-
- if (node.isRight()) {
- TitanOperationStatus status = node.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Remove Component Instance");
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Remove Component Instance");
- log.debug("Failed to delete component instance {}. status is {}", componentInstanceUid, status);
- return Either.right(status);
- }
-
- TitanOperationStatus isComponentInstOfComponent = verifyResourceInstanceUnderComponent(containerNodeType, containerComponentId, componentInstanceUid);
- if (isComponentInstOfComponent != TitanOperationStatus.OK) {
- return Either.right(isComponentInstOfComponent);
- }
-
- TitanOperationStatus status = deleteOutgoingRelationships(containerNodeType, containerComponentId, componentInstanceUid);
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
- status = deleteIncomingRelationships(containerNodeType, containerComponentId, componentInstanceUid);
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
-
- // delete associated properties
- status = deleteAssociatedProperties(componentInstanceUid);
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
- // delete associated properties
- status = deleteAssociatedAttributes(componentInstanceUid);
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
-
- // delete associated artifacts
- status = deleteAssociatedArtifacts(componentInstanceUid);
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
-
- // delete associated capability instances
- if (containerNodeType.equals(NodeTypeEnum.Resource)) {
- status = deleteAssociatedCapabilityInstances(componentInstanceUid);
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
- }
-
- // delete associated properties
- status = deleteAssociatedGroupInstances(componentInstanceUid);
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
-
- Either<ComponentInstanceData, TitanOperationStatus> deleteRI = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), componentInstanceUid, ComponentInstanceData.class);
-
- if (deleteRI.isRight()) {
- TitanOperationStatus deleteRiStatus = deleteRI.right().value();
- log.error("Failed to delete resource instance {}. status is {}", componentInstanceUid, deleteRiStatus);
- return Either.right(deleteRiStatus);
- }
-
- ComponentInstanceData deletedResourceInst = deleteRI.left().value();
-
- ComponentInstance resourceInstance = new ComponentInstance(deletedResourceInst.getComponentInstDataDefinition());
-
- return Either.left(resourceInstance);
- }
-
- private TitanOperationStatus deleteAssociatedGroupInstances(String componentInstanceUid) {
-
- return this.groupInstanceOperation.deleteAllGroupInstances(componentInstanceUid);
- }
-
- private TitanOperationStatus deleteAssociatedCapabilityInstances(String resourceInstanceId) {
- TitanOperationStatus status = TitanOperationStatus.OK;
-
- log.debug("Before deleting all capability instances of component istance {}.", resourceInstanceId);
- Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId,
- GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class);
-
- if (getCapabilityInstancesRes.isRight() && !getCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- status = getCapabilityInstancesRes.right().value();
- log.debug("Failed to retrieve capability Instances of resource instance {}. Status is {}", resourceInstanceId, status);
- }
- if (getCapabilityInstancesRes.isLeft()) {
- for (ImmutablePair<CapabilityInstData, GraphEdge> capabilityInstancePair : getCapabilityInstancesRes.left().value()) {
- Either<CapabilityInstData, TitanOperationStatus> deleteCababilityInstanceRes = capabilityInstanceOperation.deleteCapabilityInstanceFromResourceInstance(resourceInstanceId, capabilityInstancePair.getLeft().getUniqueId());
- if (deleteCababilityInstanceRes.isRight()) {
- status = deleteCababilityInstanceRes.right().value();
- }
- }
- }
- log.debug("After deleting all capability instances of component istance {}. Status is {}", resourceInstanceId, status);
- return status;
- }
-
- private TitanOperationStatus deleteAssociatedArtifacts(String resourceInstanceUid) {
-
- Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> artifactRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid, GraphEdgeLabels.ARTIFACT_REF,
- NodeTypeEnum.ArtifactRef, ArtifactData.class);
-
- if (artifactRes.isRight()) {
- TitanOperationStatus status = artifactRes.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find artifacts of resource instance {}. status is {}", resourceInstanceUid, status);
- return status;
- }
- } else {
-
- List<ImmutablePair<ArtifactData, GraphEdge>> artifactPairs = artifactRes.left().value();
- for (ImmutablePair<ArtifactData, GraphEdge> pair : artifactPairs) {
- String uniqueId = (String) pair.left.getUniqueId();
- Either<ArtifactData, TitanOperationStatus> removeArifactFromGraph = artifactOperation.removeArtifactOnGraph(resourceInstanceUid, uniqueId, NodeTypeEnum.ResourceInstance, true);
- if (removeArifactFromGraph.isRight()) {
- TitanOperationStatus status = removeArifactFromGraph.right().value();
- log.error("Failed to delete artifact of resource instance {}. status is {}", resourceInstanceUid, status);
- return status;
- }
-
- }
- }
-
- return TitanOperationStatus.OK;
-
- }
-
- private TitanOperationStatus deleteAssociatedProperties(String resourceInstanceUid) {
- final GraphEdgeLabels edgeConectingToRI = GraphEdgeLabels.PROPERTY_VALUE;
- final NodeTypeEnum elementTypeToDelete = NodeTypeEnum.PropertyValue;
- return deleteAssociatedRIElements(elementTypeToDelete, edgeConectingToRI, resourceInstanceUid, () -> PropertyValueData.class);
-
- }
-
- private TitanOperationStatus deleteAssociatedAttributes(String resourceInstanceUid) {
- final GraphEdgeLabels edgeConectingToRI = GraphEdgeLabels.ATTRIBUTE_VALUE;
- final NodeTypeEnum elementTypeToDelete = NodeTypeEnum.AttributeValue;
- return deleteAssociatedRIElements(elementTypeToDelete, edgeConectingToRI, resourceInstanceUid, () -> AttributeValueData.class);
- }
-
- private <T extends GraphNode> TitanOperationStatus deleteAssociatedRIElements(NodeTypeEnum elementTypeToDelete, GraphEdgeLabels edgeConectingToRI, String resourceInstanceUid, Supplier<Class<T>> classGen) {
-
- Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> elementsNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid, edgeConectingToRI, elementTypeToDelete,
- classGen.get());
-
- if (elementsNodesRes.isRight()) {
- TitanOperationStatus status = elementsNodesRes.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements", "Failed to find the elements of resource instance " + resourceInstanceUid + ". status is " + status, ErrorSeverity.ERROR);
- return status;
- }
- } else {
-
- List<ImmutablePair<T, GraphEdge>> relationshipNodes = elementsNodesRes.left().value();
- if (relationshipNodes != null) {
- for (ImmutablePair<T, GraphEdge> immutablePair : relationshipNodes) {
- T elementValueDataData = immutablePair.getKey();
- Either<T, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(elementValueDataData, classGen.get());
- if (deleteNode.isRight()) {
- TitanOperationStatus status = deleteNode.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements", "Failed to delete element value node " + elementValueDataData + ". status is " + status, ErrorSeverity.ERROR);
- return status;
- }
- }
- }
-
- }
-
- return TitanOperationStatus.OK;
- }
-
- /**
- * delete all relationship instance nodes which has an outgoing edge to a given resource instance
- *
- * @param resourceInstanceUid
- * @return
- */
- private TitanOperationStatus deleteIncomingRelationships(NodeTypeEnum componentType, String componentId, String resourceInstanceUid) {
-
- Either<List<RequirementCapabilityRelDef>, TitanOperationStatus> relationsForTarget = getRelationsForTarget(resourceInstanceUid);
- if (relationsForTarget.isRight()) {
- TitanOperationStatus status = relationsForTarget.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find the relationships of resource instance {}. status is {}", resourceInstanceUid, status);
- return status;
- }
- } else {
- List<RequirementCapabilityRelDef> relList = relationsForTarget.left().value();
- for (RequirementCapabilityRelDef relation : relList) {
- Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances = dissociateResourceInstances(componentId, componentType, relation, true);
- if (dissociateResourceInstances.isRight()) {
- log.error("failed to diassociate component instance {} and component instance {} under component {}. error is {}", relation.getFromNode(), relation.getToNode(), componentId);
- return TitanOperationStatus.GENERAL_ERROR;
- }
- }
- }
- return TitanOperationStatus.OK;
- }
-
- /**
- * delete all relationship instance nodes which has an incoming edge from a given resource instance
- *
- * @param resourceInstanceUid
- * @return
- */
- private TitanOperationStatus deleteOutgoingRelationships(NodeTypeEnum componentType, String componentId, String resourceInstanceUid) {
-
- Either<List<RequirementCapabilityRelDef>, TitanOperationStatus> relationsForSource = getRelationsForSource(resourceInstanceUid);
- if (relationsForSource.isRight()) {
- TitanOperationStatus status = relationsForSource.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find the relationships of resource instance {}. status is {}", resourceInstanceUid, status);
- return status;
- }
- } else {
- List<RequirementCapabilityRelDef> relList = relationsForSource.left().value();
- for (RequirementCapabilityRelDef relation : relList) {
- Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances = dissociateResourceInstances(componentId, componentType, relation, true);
- if (dissociateResourceInstances.isRight()) {
- log.error("failed to diassociate component instance {} and component instance {} under component {}. error is {}", relation.getFromNode(), relation.getToNode(), componentId);
- return TitanOperationStatus.GENERAL_ERROR;
- }
- }
- }
- return TitanOperationStatus.OK;
- }
-
- /**
- * delete relationship instance nodes
- *
- * @param relationshipNodes
- * @return
- */
- private TitanOperationStatus deleteRelationshipNodes(List<ImmutablePair<RelationshipInstData, GraphEdge>> relationshipNodes) {
-
- if (relationshipNodes != null) {
- for (ImmutablePair<RelationshipInstData, GraphEdge> immutablePair : relationshipNodes) {
- RelationshipInstData relationshipTypeImplData = immutablePair.getKey();
- Either<RelationshipInstData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(relationshipTypeImplData, RelationshipInstData.class);
- if (deleteNode.isRight()) {
- TitanOperationStatus status = deleteNode.right().value();
- log.error("Failed to delete relationship node {}. status is {}", relationshipTypeImplData, status);
- return status;
- }
- }
- }
-
- return TitanOperationStatus.OK;
- }
-
- public Either<List<RelationshipInstData>, TitanOperationStatus> disconnectResourcesInService(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef) {
-
- if (requirementDef.getRelationships() == null) {
- log.debug("No relation pair in request [ {} ]", requirementDef);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
-
- String fromResInstanceUid = requirementDef.getFromNode();
- String toResInstanceUid = requirementDef.getToNode();
-
- // DE191707
- TitanOperationStatus isResourceInstOfService = verifyResourceInstanceUnderComponent(nodeType, componentId, fromResInstanceUid);
- if (isResourceInstOfService != TitanOperationStatus.OK) {
- return Either.right(isResourceInstOfService);
- }
- isResourceInstOfService = verifyResourceInstanceUnderComponent(nodeType, componentId, toResInstanceUid);
- if (isResourceInstOfService != TitanOperationStatus.OK) {
- return Either.right(isResourceInstOfService);
- }
-
- List<RequirementAndRelationshipPair> relationPairList = requirementDef.getRelationships();
-
- Either<TitanVertex, TitanOperationStatus> riFrom = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstanceUid);
- if (riFrom.isRight()) {
- log.debug("Failed to fetch component instance {}. error {}", fromResInstanceUid, riFrom.right().value());
- return Either.right(riFrom.right().value());
- }
- Iterator<Edge> edgeIter = riFrom.left().value().edges(Direction.OUT, GraphEdgeLabels.RELATIONSHIP_INST.getProperty());
- if (edgeIter == null) {
- log.debug("No edges with label {} for owner RI {}", GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED.getProperty(), fromResInstanceUid);
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
- List<RelationshipInstData> deletedRelations = new ArrayList<>();
- Set<String> vertexToDelete = new HashSet<String>();
- while (edgeIter.hasNext()) {
- TitanEdge edge = (TitanEdge) edgeIter.next();
- String name = (String) edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value();
- for (RequirementAndRelationshipPair relationPair : relationPairList) {
- if (relationPair.getRequirement().equals(name)) {
- TitanVertex inVertex = edge.inVertex();
- String requirementId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.REQUIREMENT_ID.getProperty());
- String capabiltyId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.CAPABILITY_ID.getProperty());
- String requirementOwnerId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.REQUIREMENT_OWNER_ID.getProperty());
- String capabiltyOwnerId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.CAPABILITY_OWNER_ID.getProperty());
- String relationVertexId = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
-
- // verify vs requirement id and owner ids. ( for
- // requirements with same name)
- if (requirementId.equals(relationPair.getRequirementUid()) && capabiltyId.equals(relationPair.getCapabilityUid()) && requirementOwnerId.equals(relationPair.getRequirementOwnerId())
- && capabiltyOwnerId.equals(relationPair.getCapabilityOwnerId())) {
- vertexToDelete.add(relationVertexId);
- }
- }
- }
- }
- log.debug("relation node with ids: {} are going to be deleted", vertexToDelete);
- for (String relationVertexId : vertexToDelete) {
- // remove relation vertex
- Either<RelationshipInstData, TitanOperationStatus> relationNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipInst), relationVertexId, RelationshipInstData.class);
- if (relationNode.isRight()) {
- log.debug("Failed to delete relation node with id {}. error {}", relationVertexId, relationNode.right().value());
- return Either.right(relationNode.right().value());
- }
- RelationshipInstData deletedRelation = relationNode.left().value();
- deletedRelations.add(deletedRelation);
- }
- if (deletedRelations.size() > 0) {
- return Either.left(deletedRelations);
- }
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- @Override
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef, boolean inTransaction) {
-
- String fromResInstanceUid = requirementDef.getFromNode();
- String toResInstanceUid = requirementDef.getToNode();
- String requirement = requirementDef.getRelationships().get(0).getRequirement();
- Either<RequirementCapabilityRelDef, StorageOperationStatus> result = null;
- try {
-
- Either<List<RelationshipInstData>, TitanOperationStatus> dissociateRes = disconnectResourcesInService(componentId, nodeType, requirementDef);
- if (dissociateRes.isRight()) {
- TitanOperationStatus status = dissociateRes.right().value();
- log.error("Failed to dissociate resource instance {} from resource instance {} in service {}. status is {}", fromResInstanceUid, toResInstanceUid, componentId, status);
- BeEcompErrorManager.getInstance().logBeDaoSystemError("dissociateComponentInstances");
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- StorageOperationStatus updateCalculatedCapReqResult = updateCalculatedCapReq(requirementDef, false);
- if (!updateCalculatedCapReqResult.equals(StorageOperationStatus.OK)) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "dissociateComponentInstances");
- BeEcompErrorManager.getInstance().logBeDaoSystemError("dissociateComponentInstances");
- log.debug("Failed to dissociate component instances. {}. status is {}", requirementDef, updateCalculatedCapReqResult);
- result = Either.right(updateCalculatedCapReqResult);
- return result;
- }
-
- StorageOperationStatus status;
- status = updateCustomizationUUID(requirementDef.getFromNode());
- if (status != StorageOperationStatus.OK) {
- result = Either.right(status);
- return result;
- }
- status = updateCustomizationUUID(requirementDef.getToNode());
- if (status != StorageOperationStatus.OK) {
- result = Either.right(status);
- return result;
- }
-
- List<RelationshipInstData> relationshipInstData = dissociateRes.left().value();
- RequirementCapabilityRelDef capabilityRelDef = buildCapabilityResult(fromResInstanceUid, toResInstanceUid, requirement, relationshipInstData);
-
- result = Either.left(capabilityRelDef);
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- commitOrRollback(result);
- }
- }
-
- }
-
- private StorageOperationStatus updateCalculatedCapReq(RequirementCapabilityRelDef capabilityRelDef, boolean associate) {
- GraphEdgeLabels requirmentNewLabel = associate ? GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED : GraphEdgeLabels.CALCULATED_REQUIREMENT;
-
- GraphEdgeLabels requirmentCurrentLabel = associate ? GraphEdgeLabels.CALCULATED_REQUIREMENT : GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED;
-
- GraphEdgeLabels capabilityNewLabel = associate ? GraphEdgeLabels.CALCULATED_CAPABILITY_FULLFILLED : GraphEdgeLabels.CALCULATED_CAPABILITY;
-
- GraphEdgeLabels capabilityCurrentLabel = associate ? GraphEdgeLabels.CALCULATED_CAPABILITY : GraphEdgeLabels.CALCULATED_CAPABILITY_FULLFILLED;
-
- List<RequirementAndRelationshipPair> relationships = capabilityRelDef.getRelationships();
- for (RequirementAndRelationshipPair pair : relationships) {
- StorageOperationStatus status = updateRequirementEdges(requirmentNewLabel, requirmentCurrentLabel, pair, capabilityRelDef.getFromNode());
- if (!status.equals(StorageOperationStatus.OK)) {
- return status;
- }
- status = updateCapabiltyEdges(capabilityNewLabel, capabilityCurrentLabel, pair, capabilityRelDef.getToNode());
- if (!status.equals(StorageOperationStatus.OK)) {
- return status;
- }
- }
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus updateRequirementEdges(GraphEdgeLabels requirmentNewLabel, GraphEdgeLabels requirmentCurrentLabel, RequirementAndRelationshipPair pair, String requirementOwnerId) {
- Either<TitanVertex, TitanOperationStatus> reqOwnerRI = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), requirementOwnerId);
- if (reqOwnerRI.isRight()) {
- log.debug("Failed to fetch requirment Owner by Id {} error {}", requirementOwnerId, reqOwnerRI.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(reqOwnerRI.right().value());
- }
- Iterator<Edge> edgeIter = reqOwnerRI.left().value().edges(Direction.OUT, requirmentCurrentLabel.name(), requirmentNewLabel.name());
- if (edgeIter == null) {
- log.debug("No edges with label {} for owner RI {}", requirmentCurrentLabel, requirementOwnerId);
- return StorageOperationStatus.GENERAL_ERROR;
- }
- boolean associate = requirmentNewLabel.equals(GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED) ? true : false;
- while (edgeIter.hasNext()) {
- TitanEdge edge = (TitanEdge) edgeIter.next();
- String name = (String) edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value();
- if (pair.getRequirement().equals(name)) {
- TitanVertex reqVertex = edge.inVertex();
- String requirementId = (String) titanGenericDao.getProperty(reqVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- // verify vs requirement id . ( for requirements with same name)
- if (requirementId.equals(pair.getRequirementUid())) {
- String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
- if (ownerIdOnEdge.equals(pair.getRequirementOwnerId())) {
- String requiredOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
- String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
-
- String requiredOccurrencesNew = "0";
- String leftOccurrencesNew = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES;
- if (requiredOccurrences != null) {
- Integer iOccurrences = Integer.parseInt(requiredOccurrences);
- if (associate) {
- if (iOccurrences > 0) {
- iOccurrences--;
- requiredOccurrencesNew = iOccurrences.toString();
- }
- } else {
- String reqMinOccurrences = (String) titanGenericDao.getProperty(reqVertex, GraphPropertiesDictionary.MIN_OCCURRENCES.getProperty());
- if (reqMinOccurrences == null) {
- reqMinOccurrences = RequirementDataDefinition.MIN_OCCURRENCES;
- }
- if (Integer.parseInt(reqMinOccurrences) > iOccurrences) {
- iOccurrences++;
- requiredOccurrencesNew = iOccurrences.toString();
- }
- }
- }
- Map<String, Object> properties = titanGenericDao.getProperties(edge);
- properties.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requiredOccurrencesNew);
-
- if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
- Integer iOccurrences = Integer.parseInt(leftOccurrences);
- if (associate) {
- if (iOccurrences > 0) {
- iOccurrences--;
- }
- } else {
- iOccurrences++;
- }
- leftOccurrencesNew = iOccurrences.toString();
- properties.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), leftOccurrencesNew);
- if ((associate && iOccurrences == 0) || (!associate && iOccurrences == 1)) {
- // move edge to full filled state
- TitanVertex outVertex = edge.outVertex();
- TitanEdge newEdge = outVertex.addEdge(requirmentNewLabel.getProperty(), reqVertex);
- titanGenericDao.setProperties(newEdge, properties);
- edge.remove();
- } else {
- titanGenericDao.setProperties(edge, properties);
- }
- } else {
- leftOccurrencesNew = leftOccurrences;
- properties.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), leftOccurrencesNew);
- titanGenericDao.setProperties(edge, properties);
- }
- break;
- }
- }
- }
- }
- return StorageOperationStatus.OK;
-
- }
-
- private StorageOperationStatus updateCapabiltyEdges(GraphEdgeLabels capabiltyNewLabel, GraphEdgeLabels capabiltyCurrentLabel, RequirementAndRelationshipPair pair, String capabiltyOwnerId) {
- Either<TitanVertex, TitanOperationStatus> capOwnerRI = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), capabiltyOwnerId);
- if (capOwnerRI.isRight()) {
- log.debug("Failed to fetch requirment Owner by Id {}. error {}", capabiltyOwnerId, capOwnerRI.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(capOwnerRI.right().value());
- }
- Iterator<Edge> edgeIter = capOwnerRI.left().value().edges(Direction.OUT, capabiltyCurrentLabel.name(), capabiltyNewLabel.name());
- if (edgeIter == null) {
- log.debug("No edges with label {} for owner RI {}", capabiltyCurrentLabel, capabiltyOwnerId);
- return StorageOperationStatus.GENERAL_ERROR;
- }
- boolean associate = capabiltyNewLabel.equals(GraphEdgeLabels.CALCULATED_CAPABILITY_FULLFILLED) ? true : false;
-
- while (edgeIter.hasNext()) {
- TitanEdge edge = (TitanEdge) edgeIter.next();
- TitanVertex capVertex = edge.inVertex();
- // edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value();
-
- String capabiltyId = (String) titanGenericDao.getProperty(capVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- // verify vs capability id . ( for capabilty with same name)
- if (capabiltyId.equals(pair.getCapabilityUid())) {
- String ownerIdOnEdge = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
- if (ownerIdOnEdge.equals(pair.getCapabilityOwnerId())) {
-
- String requiredOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
- String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
-
- String requiredOccurrencesNew = "0";
- String leftOccurrencesNew = CapabilityDataDefinition.MAX_OCCURRENCES;
- if (requiredOccurrences != null) {
- Integer iOccurrences = Integer.parseInt(requiredOccurrences);
- if (associate) {
- if (iOccurrences > 0) {
- iOccurrences--;
- requiredOccurrencesNew = iOccurrences.toString();
- }
- } else {
- String reqMinOccurrences = (String) titanGenericDao.getProperty(capVertex, GraphPropertiesDictionary.MIN_OCCURRENCES.getProperty());
- if (reqMinOccurrences == null) {
- reqMinOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES;
- }
- if (Integer.parseInt(reqMinOccurrences) > iOccurrences) {
- iOccurrences++;
- requiredOccurrencesNew = iOccurrences.toString();
- }
- }
- }
- Map<String, Object> properties = titanGenericDao.getProperties(edge);
- properties.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requiredOccurrencesNew);
-
- if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
- Integer iOccurrences = Integer.parseInt(leftOccurrences);
- if (associate) {
- if (iOccurrences > 0) {
- iOccurrences--;
- }
- } else {
- iOccurrences++;
- }
- leftOccurrencesNew = iOccurrences.toString();
- properties.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), leftOccurrencesNew);
- if ((associate && iOccurrences == 0) || (!associate && iOccurrences == 1)) {
- // move edge to full filled state
- TitanVertex outVertex = edge.outVertex();
- TitanEdge newEdge = outVertex.addEdge(capabiltyNewLabel.getProperty(), capVertex);
- titanGenericDao.setProperties(newEdge, properties);
- edge.remove();
- } else {
- titanGenericDao.setProperties(edge, properties);
- }
- } else {
- properties.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), leftOccurrencesNew);
- titanGenericDao.setProperties(edge, properties);
- }
- break;
- }
- }
- }
- return StorageOperationStatus.OK;
- }
-
- @Override
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef) {
-
- return dissociateResourceInstances(serviceId, nodeType, requirementDef, false);
- }
-
- private RequirementCapabilityRelDef buildCapabilityResult(String fromResInstanceUid, String toResInstanceUid, String requirement, List<RelationshipInstData> relationshipInstDataList) {
-
- RequirementCapabilityRelDef capabilityRelDef = new RequirementCapabilityRelDef();
- capabilityRelDef.setFromNode(fromResInstanceUid);
- capabilityRelDef.setToNode(toResInstanceUid);
- List<RequirementAndRelationshipPair> relationships = new ArrayList<RequirementAndRelationshipPair>();
- for (RelationshipInstData relationshipInstData : relationshipInstDataList) {
- RelationshipImpl relationshipImpl = new RelationshipImpl();
- relationshipImpl.setType(relationshipInstData.getType());
- RequirementAndRelationshipPair reqRel = new RequirementAndRelationshipPair(requirement, relationshipImpl);
- capabilityRelDef.setRelationships(relationships);
- reqRel.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId());
- reqRel.setCapabilityUid(relationshipInstData.getCapabiltyId());
- reqRel.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId());
- reqRel.setRequirementUid(relationshipInstData.getRequirementId());
- relationships.add(reqRel);
- }
- return capabilityRelDef;
-
- }
-
- public Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService(String componentId, NodeTypeEnum nodeType, String fromResInstanceUid, String toResInstanceUid, RequirementAndRelationshipPair relationPair) {
- String relationship = null;
- String requirement = relationPair.getRequirement();
- if (relationPair.getRelationship() != null) {
- relationship = relationPair.getRelationship().getType();
- }
-
- log.debug("Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid, toResInstanceUid, componentId, requirement);
-
- Either<ComponentInstanceData, TitanOperationStatus> fromResourceInstDataRes = findMandatoryResourceInstData(fromResInstanceUid);
- if (fromResourceInstDataRes.isRight()) {
- TitanOperationStatus status = fromResourceInstDataRes.right().value();
- log.error("Failed to find resource instance {}. status is {}", fromResInstanceUid, status);
- return Either.right(status);
- }
- ComponentInstanceData fromCI = fromResourceInstDataRes.left().value();
- ComponentInstanceData fromResourceInstanceData = fromCI;
- Either<ComponentInstanceData, TitanOperationStatus> toResourceInstDataRes = findMandatoryResourceInstData(toResInstanceUid);
- if (toResourceInstDataRes.isRight()) {
- TitanOperationStatus status = toResourceInstDataRes.right().value();
- log.error("Failed to find resource instance {}. status is {}", toResInstanceUid, status);
- return Either.right(status);
- }
- ComponentInstanceData toCI = toResourceInstDataRes.left().value();
- ComponentInstanceData toResourceInstanceData = toCI;
- // THE component NodeTypeEnum should be sent
- TitanOperationStatus isResourceInstOfService = verifyResourceInstanceUnderComponent(nodeType, componentId, fromResInstanceUid);
- if (isResourceInstOfService != TitanOperationStatus.OK) {
- return Either.right(isResourceInstOfService);
- }
- isResourceInstOfService = verifyResourceInstanceUnderComponent(nodeType, componentId, toResInstanceUid);
- if (isResourceInstOfService != TitanOperationStatus.OK) {
- return Either.right(isResourceInstOfService);
- }
-
- Either<ImmutablePair<RelationshipTypeData, String>, TitanOperationStatus> isValidRes = validateRequirementVsCapability(fromResourceInstanceData, toResourceInstanceData, requirement, relationship, relationPair);
- if (isValidRes.isRight()) {
- TitanOperationStatus status = isValidRes.right().value();
- log.error("Failed to validate requirement {} between resource instance {} to resource instance {}. status is {}", requirement, fromResInstanceUid, toResInstanceUid, status);
- return Either.right(status);
- }
-
- RelationshipTypeData relationshipTypeData = isValidRes.left().value().getKey();
- String capabilityName = isValidRes.left().value().getValue();
- RelationshipInstData relationshipInstData = buildRelationshipInstData(fromResInstanceUid, requirement, relationshipTypeData, relationPair);
- Either<RelationshipInstData, TitanOperationStatus> createNode = createRelationshipInstData(fromCI, relationshipInstData, relationshipTypeData, requirement);
-
- if (createNode.isRight()) {
- return Either.right(createNode.right().value());
- }
- RelationshipInstData createdRelInstData = createNode.left().value();
- Either<GraphRelation, TitanOperationStatus> associateResInst = associateRelationshipInstToTarget(toCI, requirement, capabilityName, createdRelInstData);
-
- if (associateResInst.isRight()) {
- TitanOperationStatus status = associateResInst.right().value();
- log.error("Failed to associate relationship instance {} to target node {}. status is {}", createdRelInstData.getUniqueId(), toResInstanceUid, status);
- return Either.right(status);
- }
-
- return Either.left(createNode.left().value());
- }
-
- private TitanOperationStatus verifyResourceInstanceUnderComponent(NodeTypeEnum containerNodeType, String containerComponentId, String resInstanceUid) {
-
- Either<ImmutablePair<ComponentMetadataData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resInstanceUid, GraphEdgeLabels.RESOURCE_INST,
- containerNodeType, ComponentMetadataData.class);
-
- if (parentNode.isRight()) {
- TitanOperationStatus status = parentNode.right().value();
- log.error("Failed to find the service associated to the resource instance {}. status is {}", resInstanceUid, status);
- return status;
- }
-
- ImmutablePair<ComponentMetadataData, GraphEdge> componentsRes = parentNode.left().value();
- ComponentMetadataData componentMetadataData = componentsRes.getKey();
- String uniqueId = (String) componentMetadataData.getUniqueId();
-
- if (containerComponentId.equals(uniqueId)) {
- return TitanOperationStatus.OK;
- } else {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeIncorrectServiceError, "Resource Instance - verifyResourceInstanceUnderComponent", containerComponentId);
- BeEcompErrorManager.getInstance().logBeIncorrectComponentError("Resource Instance - verifyResourceInstanceUnderComponent", containerNodeType.getName(), containerComponentId);
- log.debug("The provided component id {} is not equal to the component ({}) which associated to resource instance {}", containerComponentId, uniqueId, resInstanceUid);
- return TitanOperationStatus.INVALID_ID;
- }
-
- }
-
- /**
- * find the resource instance node in graph.
- *
- * @param resInstanceUid
- * @return
- */
- private Either<ComponentInstanceData, TitanOperationStatus> findMandatoryResourceInstData(String resInstanceUid) {
- Either<ComponentInstanceData, TitanOperationStatus> resStatus = findResourceInstance(resInstanceUid);
- if (resStatus.isRight()) {
- TitanOperationStatus status = resStatus.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- return Either.right(TitanOperationStatus.INVALID_ID);
- }
- return Either.right(status);
- }
- ComponentInstanceData riData = resStatus.left().value();
- return Either.left(riData);
- }
-
- /**
- * associate relationship instance node to the target resource instance node.
- *
- * @param toResInstance
- * @param requirement
- * @param relInstData
- * @return
- */
- private Either<GraphRelation, TitanOperationStatus> associateRelationshipInstToTarget(ComponentInstanceData toResInstance, String requirement, String capabilityName, RelationshipInstData relInstData) {
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(relInstData, toResInstance, GraphEdgeLabels.CAPABILITY_NODE, props);
- log.debug("After creatingrelation between relationship instance {} to target node {}", relInstData.getUniqueId(), toResInstance.getUniqueId());
-
- return createRelation;
-
- }
-
- /**
- * create reslationship instance node and associate the reosurce instance node to it.
- *
- * @param resInstance
- * @param relationshipInstData
- * @param relationshipTypeData
- * @param requirementName
- * @return
- */
- private Either<RelationshipInstData, TitanOperationStatus> createRelationshipInstData(ComponentInstanceData resInstance, RelationshipInstData relationshipInstData, RelationshipTypeData relationshipTypeData, String requirementName) {
-
- Either<RelationshipInstData, TitanOperationStatus> createNode = titanGenericDao.createNode(relationshipInstData, RelationshipInstData.class);
- if (createNode.isRight()) {
- TitanOperationStatus status = createNode.right().value();
- log.error("Failed to create relationship instance node in graph. status is {}", status);
- return Either.right(status);
- }
-
- RelationshipInstData createdRelationshipInst = createNode.left().value();
-
- Map<String, Object> properties = new HashMap<String, Object>();
- properties.put("name", requirementName);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(resInstance, createdRelationshipInst, GraphEdgeLabels.RELATIONSHIP_INST, properties);
- if (createRelation.isRight()) {
- TitanOperationStatus status = createRelation.right().value();
- log.error("Failed to associate resource instance {} to relationship instance {}. status is {}", resInstance.getUniqueIdKey(), createdRelationshipInst.getUniqueId(), status);
- return Either.right(status);
- }
-
- return Either.left(createdRelationshipInst);
- }
-
- /**
- * check whether we can associate resource instances for a given requirement.
- *
- * 1. check the source resource instance contains the requirement
- *
- * 2. check the target resource instance contains a capability with the same name as the requirement
- *
- * @param fromResInstance
- * @param toResInstance
- * @param requirement
- * @param relationship
- * @param relationPair
- * @return
- */
- private Either<ImmutablePair<RelationshipTypeData, String>, TitanOperationStatus> validateRequirementVsCapability(ComponentInstanceData fromResInstance, ComponentInstanceData toResInstance, String requirement, String relationship,
- RequirementAndRelationshipPair relationPair) {
-
- String fromResourceUid = fromResInstance.getComponentInstDataDefinition().getComponentUid();
-
- String toResourceUid = toResInstance.getComponentInstDataDefinition().getComponentUid();
- Either<CapabilityDefinition, StorageOperationStatus> capabilityDefinitionE = capabilityOperation.getCapability(relationPair.getCapabilityUid(), true);
- if (capabilityDefinitionE.isRight()) {
- log.error("The capability cannot be found {}", relationPair.getCapabilityUid());
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- Either<RequirementDefinition, TitanOperationStatus> requirementDefinitionE = requirementOperation.getRequirement(relationPair.getRequirementUid());
- if (requirementDefinitionE.isRight()) {
- log.error("The requirement cannot be found {}", relationPair.getRequirementUid());
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- RequirementDefinition requirementDefinition = requirementDefinitionE.left().value();
- String fetchedRequirementRelationship = requirementDefinition.getRelationship();
-
- String fetchedRequirementCapability = requirementDefinition.getCapability();
- // String fetchedRequirementNodeName = requirementDefinition.getNode();
-
- TitanOperationStatus status = validateAvailableRequirement(fromResInstance, relationPair);
- if (!status.equals(TitanOperationStatus.OK)) {
- log.error("The requirement isn't available, status {}", status);
- return Either.right(status);
- }
- status = validateAvailableCapabilty(toResInstance, relationPair);
- if (!status.equals(TitanOperationStatus.OK)) {
- log.error("The capabilty isn't available, status {}", status);
- return Either.right(status);
- }
- Either<ComponentInstanceData, TitanOperationStatus> originCapabilty = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), relationPair.getCapabilityOwnerId(), ComponentInstanceData.class);
- if (originCapabilty.isRight()) {
- log.error("Failed to fetch the origin resource for capabilty resource instance with id {}, error {}", relationPair.getCapabilityOwnerId(), originCapabilty.right().value());
- return Either.right(originCapabilty.right().value());
- }
- // String originCapabId =
- // originCapabilty.left().value().getComponentInstDataDefinition().getComponentUid();
-
- // List<String> capabilitySources = new ArrayList<>();
- // TitanOperationStatus capabiltySourcesResult =
- // resourceOperation.fillResourceDerivedListFromGraph(originCapabId,
- // capabilitySources);
- // if (!TitanOperationStatus.OK.equals(capabiltySourcesResult)) {
- // log.error("Failed to fill capabilty cources for resource with id " +
- // originCapabId + " , error " + capabiltySourcesResult);
- // return Either.right(originCapabilty.right().value());
- // }
- CapabilityDefinition capabilityDefinition = capabilityDefinitionE.left().value();
- String capabilityName = requirement;
-
- log.debug("The capability {} of resource {} appropriates to requirement {} on resource {}", capabilityDefinition, toResourceUid, requirement, fromResourceUid);
- String capabilityType = capabilityDefinition.getType();
-
- if (false == fetchedRequirementCapability.equals(capabilityType)) {
- log.error("The capability type in the requirement ({}) does not equal to the capability on the resource {} ({})", fetchedRequirementCapability, toResourceUid, capabilityType);
- return Either.right(TitanOperationStatus.MATCH_NOT_FOUND);
- }
-
- // if (fetchedRequirementNodeName != null &&
- // !capabilitySources.contains(fetchedRequirementNodeName)) {
- // log.error("The target resource instance " + toResourceUid + " is not
- // of type " + fetchedRequirementNodeName);
- // return Either.right(TitanOperationStatus.MATCH_NOT_FOUND);
- // }
-
- RelationshipTypeData relationshipTypeData = new RelationshipTypeData();
- relationshipTypeData.getRelationshipTypeDataDefinition().setType(fetchedRequirementRelationship);
-
- ImmutablePair<RelationshipTypeData, String> result = new ImmutablePair<RelationshipTypeData, String>(relationshipTypeData, capabilityName);
- return Either.left(result);
- }
-
- private TitanOperationStatus validateAvailableRequirement(ComponentInstanceData fromResInstance, RequirementAndRelationshipPair relationPair) {
- Either<TitanVertex, TitanOperationStatus> fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstance.getUniqueId());
- if (fromRi.isRight()) {
- log.debug("Failed to fetch component instance {} error {}", fromResInstance.getUniqueId(), fromRi.right().value());
- return fromRi.right().value();
- }
- Iterator<Edge> edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_REQUIREMENT.name());
- if (edgeIter == null || !edgeIter.hasNext()) {
- log.debug("No available CALCULATED_REQUIREMENT edges. All full filled for RI {}", fromResInstance.getUniqueId());
- return TitanOperationStatus.MATCH_NOT_FOUND;
- }
- boolean exist = false;
- while (edgeIter.hasNext()) {
- Edge edge = edgeIter.next();
- TitanVertex reqVertex = (TitanVertex) edge.inVertex();
- String reqId = (String) titanGenericDao.getProperty(reqVertex, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement));
- if (reqId.equals(relationPair.getRequirementUid())) {
- String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
- if (ownerIdOnEdge.equals(relationPair.getRequirementOwnerId())) {
- String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
- if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
- Integer leftIntValue = Integer.parseInt(leftOccurrences);
- if (leftIntValue > 0) {
- exist = true;
- }
- } else {
- exist = true;
- }
- break;
- }
- }
- }
- return exist ? TitanOperationStatus.OK : TitanOperationStatus.MATCH_NOT_FOUND;
- }
-
- private TitanOperationStatus validateAvailableCapabilty(ComponentInstanceData toResInstance, RequirementAndRelationshipPair relationPair) {
- Either<TitanVertex, TitanOperationStatus> fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), toResInstance.getUniqueId());
- if (fromRi.isRight()) {
- log.debug("Failed to fetch component instance {}. error {}", toResInstance.getUniqueId(), fromRi.right().value());
- return fromRi.right().value();
- }
- Iterator<Edge> edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_CAPABILITY.name());
- if (edgeIter == null || !edgeIter.hasNext()) {
- log.debug("No available CALCULATED_CAPABILITY edges. All full filled for RI {}", toResInstance.getUniqueId());
- return TitanOperationStatus.MATCH_NOT_FOUND;
- }
- boolean exist = false;
- while (edgeIter.hasNext()) {
- Edge edge = edgeIter.next();
- TitanVertex reqVertex = (TitanVertex) edge.inVertex();
- String capId = (String) titanGenericDao.getProperty(reqVertex, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability));
- if (capId.equals(relationPair.getCapabilityUid())) {
- String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
- if (ownerIdOnEdge.equals(relationPair.getCapabilityOwnerId())) {
- String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
- if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
- Integer leftIntValue = Integer.parseInt(leftOccurrences);
- if (leftIntValue > 0) {
- exist = true;
- }
- } else {
- exist = true;
- }
- break;
- }
- }
- }
- return exist ? TitanOperationStatus.OK : TitanOperationStatus.NOT_FOUND;
- }
-
- private List<ImmutablePair<String, CapabilityDefinition>> findCapabilityOfType(Map<String, CapabilityDefinition> capabilities, String fetchedRequirementCapability) {
-
- List<ImmutablePair<String, CapabilityDefinition>> result = new ArrayList<ImmutablePair<String, CapabilityDefinition>>();
-
- if (capabilities == null) {
- return null;
- }
-
- for (Entry<String, CapabilityDefinition> entry : capabilities.entrySet()) {
- CapabilityDefinition capabilityDefinition = entry.getValue();
- String type = capabilityDefinition.getType();
- if (fetchedRequirementCapability.equals(type)) {
- ImmutablePair<String, CapabilityDefinition> pair = new ImmutablePair<String, CapabilityDefinition>(entry.getKey(), capabilityDefinition);
- result.add(pair);
- }
- }
-
- return result;
- }
-
- protected TitanOperationStatus validateTheTargetResourceInstance(String fetchedRequirementNodeName, String resourceUid) {
-
- if (fetchedRequirementNodeName == null) {
- return TitanOperationStatus.OK;
- }
-
- List<ResourceMetadataData> resourcesPathList = new ArrayList<ResourceMetadataData>();
- TitanOperationStatus status = resourceOperation.findResourcesPathRecursively(resourceUid, resourcesPathList);
- if (status != TitanOperationStatus.OK) {
- log.error("Failed to find the parent list of resource {}. status is {}", resourceUid, status);
- return status;
- }
-
- boolean found = false;
- if (resourcesPathList != null) {
- for (ResourceMetadataData resourceData : resourcesPathList) {
- String resourceName = resourceData.getMetadataDataDefinition().getName();
- if (fetchedRequirementNodeName.equals(resourceName)) {
- found = true;
- log.debug("The resource {} is of type {}", resourceData.getUniqueId(), fetchedRequirementNodeName);
- break;
- }
- }
- }
-
- if (true == found) {
- return TitanOperationStatus.OK;
- } else {
- return TitanOperationStatus.MATCH_NOT_FOUND;
- }
-
- }
-
- private RelationshipInstData buildRelationshipInstData(String fromResInstanceUid, String requirement, RelationshipTypeData relationshipTypeData, RequirementAndRelationshipPair relationPair) {
-
- RelationshipInstData relationshipInstData = new RelationshipInstData();
- relationshipInstData.setUniqueId(UniqueIdBuilder.buildRelationsipInstInstanceUid(fromResInstanceUid, requirement));
- String type = null;
- if (relationshipTypeData != null) {
- type = relationshipTypeData.getRelationshipTypeDataDefinition().getType();
- }
-
- relationshipInstData.setType(type);
- Long creationDate = System.currentTimeMillis();
- relationshipInstData.setCreationTime(creationDate);
- relationshipInstData.setModificationTime(creationDate);
- relationshipInstData.setCapabilityOwnerId(relationPair.getCapabilityOwnerId());
- relationshipInstData.setRequirementOwnerId(relationPair.getRequirementOwnerId());
- relationshipInstData.setCapabiltyId(relationPair.getCapabilityUid());
- relationshipInstData.setRequirementId(relationPair.getRequirementUid());
-
- return relationshipInstData;
- }
-
- private Either<ComponentInstanceData, TitanOperationStatus> findResourceInstance(String resInstanceUid) {
-
- Either<ComponentInstanceData, TitanOperationStatus> node = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resInstanceUid, ComponentInstanceData.class);
-
- return node;
-
- }
-
- @Override
- public Either<ComponentInstance, StorageOperationStatus> updateResourceInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceUid, ComponentInstance resourceInstance, boolean inTransaction) {
-
- Either<ComponentInstance, StorageOperationStatus> result = null;
- try {
-
- Either<ComponentInstance, TitanOperationStatus> updateRes = updateResourceInstanceInService(serviceId, resourceInstanceUid, resourceInstance);
-
- if (updateRes.isRight()) {
- TitanOperationStatus status = updateRes.right().value();
- log.error("Failed to update resource instance {}. status is {}", resourceInstanceUid, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- ComponentInstance value = updateRes.left().value();
-
- result = Either.left(value);
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- commitOrRollback(result);
- }
- }
-
- }
-
- /**
- * prepare new resource instance object for update
- *
- * @param resourceInstance
- * @param currentInst
- * @return
- */
- private ComponentInstance normalizeResourceInstanceForUpdate(ComponentInstance resourceInstance, ComponentInstanceData currentInst) {
-
- ComponentInstance instance = new ComponentInstance();
- instance.setUniqueId((String) currentInst.getUniqueId());
- Long modificationTime = resourceInstance.getModificationTime();
- if (modificationTime == null) {
- modificationTime = System.currentTimeMillis();
- }
- instance.setModificationTime(modificationTime);
- instance.setPosX(resourceInstance.getPosX());
- instance.setPosY(resourceInstance.getPosY());
- instance.setDescription(resourceInstance.getDescription());
- instance.setName(resourceInstance.getName());
- instance.setNormalizedName(resourceInstance.getNormalizedName());
- instance.setPropertyValueCounter(resourceInstance.getPropertyValueCounter());
- instance.setAttributeValueCounter(resourceInstance.getAttributeValueCounter());
- instance.setInputValueCounter(resourceInstance.getInputValueCounter());
-
- boolean isNeedGenerate = isNeedGenerateCustomizationUUID(resourceInstance, currentInst);
- if (isNeedGenerate) {
- generateCustomizationUUID(instance);
- } else {
- instance.setCustomizationUUID(resourceInstance.getCustomizationUUID());
- }
- return instance;
- }
-
- private boolean isNeedGenerateCustomizationUUID(ComponentInstance resourceInstance, ComponentInstanceData currentInst) {
- return !currentInst.getComponentInstDataDefinition().getName().equals(resourceInstance.getName());
- }
-
- private void printDiff(ComponentInstanceData currentInst, ComponentInstance resourceInstance) {
-
- log.debug("The current Resource Instance details are : {}", currentInst);
- log.debug("The received Resource Instance details for update are :{}", resourceInstance);
-
- }
-
- @Override
- public Either<ComponentInstance, StorageOperationStatus> updateResourceInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance) {
-
- return updateResourceInstance(serviceId, nodeType, resourceInstanceName, resourceInstance, false);
- }
-
- public Either<ComponentInstance, TitanOperationStatus> updateResourceInstanceInService(String serviceId, String resourceInstanceUid, ComponentInstance resourceInstance) {
-
- log.trace("Going to update resource instance {}. Properies are {}", resourceInstanceUid, resourceInstance);
- Either<ComponentInstanceData, TitanOperationStatus> findInstRes = findResourceInstance(resourceInstanceUid);
- if (findInstRes.isRight()) {
- TitanOperationStatus status = findInstRes.right().value();
- log.error("Failed to find resource instance {}. status is {}", resourceInstanceUid, status);
- return Either.right(status);
- }
-
- ComponentInstanceData currentInst = findInstRes.left().value();
- if (log.isDebugEnabled()) {
- printDiff(currentInst, resourceInstance);
- }
-
- ComponentInstance resourceInstanceForUpdate = normalizeResourceInstanceForUpdate(resourceInstance, currentInst);
-
- ComponentInstanceData resourceInstanceData = new ComponentInstanceData(resourceInstanceForUpdate);
-
- Either<ComponentInstanceData, TitanOperationStatus> updateNodeRes = titanGenericDao.updateNode(resourceInstanceData, ComponentInstanceData.class);
- if (updateNodeRes.isRight()) {
- TitanOperationStatus status = updateNodeRes.right().value();
- log.error("Failed to update resource instance {}. status is {}", resourceInstanceUid, status);
- return Either.right(status);
- }
-
- ComponentInstanceData value = updateNodeRes.left().value();
-
- ComponentInstance instance = new ComponentInstance(value.getComponentInstDataDefinition());
-
- return Either.left(instance);
-
- }
-
- @Override
- public Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> getAllComponentInstances(String componentId, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, boolean inTransaction) {
-
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> result = null;
-
- try {
-
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resInstancesOfService = getComponentInstancesOfComponent(componentId, containerNodeType, compInstNodeType);
-
- log.trace("After fetching resource instances of component {}. result is {}", componentId, resInstancesOfService);
- if (resInstancesOfService.isRight()) {
- TitanOperationStatus status = resInstancesOfService.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find resource instances of service {}. status is {}", componentId, status);
- }
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>> immutablePair = resInstancesOfService.left().value();
- List<ComponentInstance> nodes = immutablePair.getKey();
- if (nodes == null || nodes.isEmpty()) {
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
-
- result = Either.left(immutablePair);
- return result;
- } finally {
- if (false == inTransaction) {
- commitOrRollback(result);
- }
- }
- }
-
- @Override
- public Either<Boolean, StorageOperationStatus> isComponentInstanceNameExist(String parentComponentId, NodeTypeEnum nodeType, String compInstId, String componentInstName) {
-
- Either<Boolean, StorageOperationStatus> result = null;
- Either<Boolean, TitanOperationStatus> updateRes = isComponentInstanceNameExistOnGraph(parentComponentId, nodeType, compInstId, componentInstName);
-
- if (updateRes.isRight()) {
- TitanOperationStatus status = updateRes.right().value();
- log.error("Failed to find component instance name {}. status is {}", componentInstName, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- Boolean value = updateRes.left().value();
-
- result = Either.left(value);
-
- return result;
-
- }
-
- private Either<Boolean, TitanOperationStatus> isComponentInstanceNameExistOnGraph(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName) {
-
- Either<TitanGraph, TitanOperationStatus> graphRes = titanGenericDao.getGraph();
- if (graphRes.isRight()) {
- log.debug("Failed to retrieve graph. status is {}", graphRes);
- return Either.right(graphRes.right().value());
- }
-
- TitanGraph titanGraph = graphRes.left().value();
- Iterable<TitanVertex> vertices = titanGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentComponentId).vertices();
- if (vertices == null || false == vertices.iterator().hasNext()) {
- return Either.right(TitanOperationStatus.INVALID_ID);
- }
-
- TitanVertex serviceVertex = vertices.iterator().next();
- TitanVertexQuery query = serviceVertex.query();
- query = query.labels(GraphEdgeLabels.RESOURCE_INST.getProperty());
- Iterable<Vertex> verts = query.vertices();
- if (verts == null) {
- log.debug("No edges in graph for criteria");
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
- Iterator<Vertex> vIter = verts.iterator();
- while (vIter.hasNext()) {
- Vertex vert = vIter.next();
- String resInstName = vert.value(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty());
- if (resInstName.equals(componentInstName)) {
- if (compInstId != null) {// will be null if we got here from
- // create
- // Update case - skipping if this is the same component
- // instance we are updating, that is allowing
- // update of the unchanged name on a component instance.
- // This is needed to support position only update, since
- // name should
- // always be passed in update, and in position case, the
- // name will be unchanged.
- String uniqueId = vert.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- if (uniqueId.equals(compInstId)) {
- continue;
- }
- }
- return Either.left(Boolean.TRUE);
- }
- }
- return Either.left(Boolean.FALSE);
- }
-
- /**
- * find resource instances and the relationships between the relationships of a given resource
- *
- * @param componentId
- * @return
- */
- public Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> getComponentInstancesOfComponent(String componentId, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType) {
-
- if (log.isDebugEnabled())
- log.debug("Going to fetch all resource instances under component {}", componentId);
-
- Either<ComponentMetadataData, TitanOperationStatus> componentRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(containerNodeType), componentId, ComponentMetadataData.class);
- if (componentRes.isRight()) {
- TitanOperationStatus status = componentRes.right().value();
- log.error("Failed to find component {}. status is {}", componentId, status);
- return Either.right(status);
- }
-
- Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> resourceInstancesRes = getAllComponentInstanceFromGraph(componentId, containerNodeType, true);
- if (resourceInstancesRes.isRight()) {
- TitanOperationStatus status = resourceInstancesRes.right().value();
- log.debug("Resource instance was found under component {}. status is {}", componentId, status);
- return Either.right(status);
- }
-
- List<ComponentInstance> resourcesResult = new ArrayList<ComponentInstance>();
- List<RequirementCapabilityRelDef> requirementsResult = new ArrayList<RequirementCapabilityRelDef>();
-
- List<ImmutablePair<ComponentInstanceData, GraphEdge>> resourceInstances = resourceInstancesRes.left().value();
- if (resourceInstances != null && false == resourceInstances.isEmpty()) {
- Map<String, Map<String, CapabilityDefinition>> compInstCapabilities = new HashMap<String, Map<String, CapabilityDefinition>>();
- Map<String, Map<String, RequirementDefinition>> compInstReq = new HashMap<String, Map<String, RequirementDefinition>>();
- Map<String, Map<String, ArtifactDefinition>> compInstDeploymentArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>();
- Map<String, Map<String, ArtifactDefinition>> compInstInformationalArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>();
- Map<String, Component> compInstOriginsMap = new HashMap<String, Component>();
-
- for (ImmutablePair<ComponentInstanceData, GraphEdge> immutablePair : resourceInstances) {
-
- ComponentInstanceData resourceInstanceData = immutablePair.getKey();
- if (log.isDebugEnabled())
- log.debug("Going to fetch the relationships of resource instance {}", resourceInstanceData);
-
- ComponentInstance resourceInstance = new ComponentInstance(resourceInstanceData.getComponentInstDataDefinition());
-
- TitanOperationStatus status = getFullComponentInstance(compInstCapabilities, compInstReq, compInstDeploymentArtifacts, compInstOriginsMap, resourceInstance, compInstNodeType, compInstInformationalArtifacts);
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
- resourcesResult.add(resourceInstance);
-
- Either<List<ImmutablePair<RelationshipInstData, GraphEdge>>, TitanOperationStatus> relationshipsRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance),
- (String) resourceInstanceData.getUniqueId(), GraphEdgeLabels.RELATIONSHIP_INST, NodeTypeEnum.RelationshipInst, RelationshipInstData.class);
-
- if (relationshipsRes.isRight()) {
- status = relationshipsRes.right().value();
- log.debug("After fetching all reslationships of resource instance {} under component {} . status is {}", resourceInstanceData.getUniqueId(), componentId, status);
- if (status == TitanOperationStatus.NOT_FOUND) {
- continue;
- } else {
- log.error("Failed to find relationhips of resource instance {} under component {}. status is {}", resourceInstanceData.getUniqueId(), componentId, status);
- return Either.right(status);
- }
- }
-
- String sourceResourceUid = (String) resourceInstanceData.getUniqueId();
-
- Map<String, List<ImmutablePair<String, RelationshipInstData>>> targetNodeToRelationship = new HashMap<String, List<ImmutablePair<String, RelationshipInstData>>>();
-
- List<ImmutablePair<RelationshipInstData, GraphEdge>> relationshipsImpl = relationshipsRes.left().value();
- status = populateTargetAndRelationsForGivenSource(targetNodeToRelationship, relationshipsImpl);
-
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
-
- if (targetNodeToRelationship.isEmpty()) {
- log.error("No target found for relationship instances of resource instance {}", resourceInstanceData.getUniqueId());
- return Either.right(TitanOperationStatus.INVALID_ELEMENT);
- }
-
- buildRelationsForSource(requirementsResult, sourceResourceUid, targetNodeToRelationship);
-
- }
-
- return Either.left(new ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>(resourcesResult, requirementsResult));
- } else {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- }
-
- private Either<List<RequirementCapabilityRelDef>, TitanOperationStatus> getRelationsForSource(String resourceInstanceUid) {
- Either<List<ImmutablePair<RelationshipInstData, GraphEdge>>, TitanOperationStatus> relationshipsRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid,
- GraphEdgeLabels.RELATIONSHIP_INST, NodeTypeEnum.RelationshipInst, RelationshipInstData.class);
-
- TitanOperationStatus status;
- List<RequirementCapabilityRelDef> requirementsResult = new ArrayList<RequirementCapabilityRelDef>();
-
- if (relationshipsRes.isRight()) {
- status = relationshipsRes.right().value();
- log.debug("After fetching all reslationships of resource instance {}. status is {}", resourceInstanceUid, status);
- if (status == TitanOperationStatus.NOT_FOUND) {
- return Either.left(requirementsResult);
- } else {
- log.error("Failed to find relationhips of resource instance {}. status is {}", resourceInstanceUid, status);
- return Either.right(status);
- }
- }
-
- Map<String, List<ImmutablePair<String, RelationshipInstData>>> targetNodeToRelationship = new HashMap<String, List<ImmutablePair<String, RelationshipInstData>>>();
-
- List<ImmutablePair<RelationshipInstData, GraphEdge>> relationshipsImpl = relationshipsRes.left().value();
- status = populateTargetAndRelationsForGivenSource(targetNodeToRelationship, relationshipsImpl);
-
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
-
- if (targetNodeToRelationship.isEmpty()) {
- log.error("No target found for relationship instances of resource instance {}", resourceInstanceUid);
- return Either.right(TitanOperationStatus.INVALID_ELEMENT);
- }
-
- buildRelationsForSource(requirementsResult, resourceInstanceUid, targetNodeToRelationship);
- return Either.left(requirementsResult);
- }
-
- private Either<List<RequirementCapabilityRelDef>, TitanOperationStatus> getRelationsForTarget(String resourceInstanceUid) {
-
- TitanOperationStatus status;
-
- Either<List<ImmutablePair<RelationshipInstData, GraphEdge>>, TitanOperationStatus> relationshipsRes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid,
- GraphEdgeLabels.CAPABILITY_NODE, NodeTypeEnum.RelationshipInst, RelationshipInstData.class);
-
- List<RequirementCapabilityRelDef> requirementsResult = new ArrayList<RequirementCapabilityRelDef>();
-
- if (relationshipsRes.isRight()) {
- status = relationshipsRes.right().value();
- log.debug("After fetching all reslationships of resource instance {}. status is {}", resourceInstanceUid, status);
- if (status == TitanOperationStatus.NOT_FOUND) {
- return Either.left(requirementsResult);
- } else {
- log.error("Failed to find relationhips of resource instance {}. status is {}", resourceInstanceUid, status);
- return Either.right(status);
- }
- }
-
- Map<String, List<ImmutablePair<String, RelationshipInstData>>> sourceNodeToRelationship = new HashMap<String, List<ImmutablePair<String, RelationshipInstData>>>();
-
- List<ImmutablePair<RelationshipInstData, GraphEdge>> relationshipsImpl = relationshipsRes.left().value();
- status = populateSourceAndRelationsForGivenTarget(sourceNodeToRelationship, relationshipsImpl);
-
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
-
- if (sourceNodeToRelationship.isEmpty()) {
- log.error("No target found for relationship instances of resource instance {}", resourceInstanceUid);
- return Either.right(TitanOperationStatus.INVALID_ELEMENT);
- }
-
- buildRelationsForTarget(requirementsResult, resourceInstanceUid, sourceNodeToRelationship);
- return Either.left(requirementsResult);
- }
-
- @Override
- public Either<ComponentInstance, StorageOperationStatus> getFullComponentInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType) {
- Map<String, Map<String, CapabilityDefinition>> compInstCapabilities = new HashMap<String, Map<String, CapabilityDefinition>>();
- Map<String, Map<String, RequirementDefinition>> compInstReq = new HashMap<String, Map<String, RequirementDefinition>>();
- Map<String, Map<String, ArtifactDefinition>> compInstDeploymentArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>();
- Map<String, Map<String, ArtifactDefinition>> compInstInformationalArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>();
- Map<String, Component> compInstOrigins = new HashMap<String, Component>();
-
- TitanOperationStatus fullResourceInstance = getFullComponentInstance(compInstCapabilities, compInstReq, compInstDeploymentArtifacts, compInstOrigins, componentInstance, compInstNodeType, compInstInformationalArtifacts);
- if (!fullResourceInstance.equals(TitanOperationStatus.OK)) {
- log.debug("failed to get full data of resource instance. error: {}", fullResourceInstance);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(fullResourceInstance));
- }
- return Either.left(componentInstance);
- }
-
- private TitanOperationStatus getFullComponentInstance(Map<String, Map<String, CapabilityDefinition>> compInstCapabilities, Map<String, Map<String, RequirementDefinition>> compInstReq,
- Map<String, Map<String, ArtifactDefinition>> compInstDeploymentArtifacts, Map<String, Component> compInstOrigins, ComponentInstance compInst, NodeTypeEnum compInstNodeType,
- Map<String, Map<String, ArtifactDefinition>> compInstInformationalArtifacts) {
- Component component = null;
- ComponentOperation componentOperation = getComponentOperation(compInstNodeType);
- String componentUid = compInst.getComponentUid();
- if (compInstOrigins.containsKey(componentUid)) {
- component = compInstOrigins.get(componentUid);
- } else {
- Either<Component, StorageOperationStatus> metadataComponent = componentOperation.getMetadataComponent(componentUid, true);
- if (metadataComponent.isRight()) {
- log.debug("Failed to fetch the origin component for component instance, origin Id {}, error: {}", componentUid, metadataComponent.right().value());
- return TitanOperationStatus.GENERAL_ERROR;
- }
- component = metadataComponent.left().value();
- compInstOrigins.put(componentUid, component);
-
- }
- String icon = component.getIcon();
- if (log.isDebugEnabled())
- log.debug("Fetch the resource instance icon from the resource itself. icon = {}", icon);
- compInst.setIcon(icon);
- String componentName = component.getName();
- compInst.setComponentName(componentName);
- compInst.setComponentVersion(component.getVersion());
- if (component.getComponentType() == ComponentTypeEnum.RESOURCE) {
- compInst.setToscaComponentName(((Resource) component).getToscaResourceName());
- }
-
- List<ComponentInstance> componentInstances = new ArrayList<>();
- List<String> derivedFromList = new ArrayList<String>();
-
- // For VFC/VL/CP
- if (compInstNodeType == NodeTypeEnum.Resource && ((Resource) component).getResourceType() != ResourceTypeEnum.VF) {
- resourceOperation.fillResourceDerivedListFromGraph(component.getUniqueId(), derivedFromList);
- } else {
- // Getting component instances that the origin component of this
- // component instance is their container, so we can use the logic of
- // getting req/cap from them
- // and fill this component instance with those req/cap
- Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> allComponentInstanceFromGraph = getAllComponentInstanceFromGraph(componentUid, compInstNodeType, true);
- if (allComponentInstanceFromGraph.isRight() && allComponentInstanceFromGraph.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("Couldn't fetch component instances for component {} of type {}", componentUid, compInstNodeType);
- return allComponentInstanceFromGraph.right().value();
- }
- List<ImmutablePair<ComponentInstanceData, GraphEdge>> allCIs = allComponentInstanceFromGraph.isLeft() ? allComponentInstanceFromGraph.left().value() : new ArrayList<>();
- for (ImmutablePair<ComponentInstanceData, GraphEdge> entry : allCIs) {
- componentInstances.add(new ComponentInstance(entry.left.getComponentInstDataDefinition()));
- }
- component.setComponentInstances(componentInstances);
- }
-
- StorageOperationStatus capStatus = setCompInstCapabilitiesFromGraph(compInstCapabilities, component, compInstNodeType, compInst, derivedFromList);
- if (capStatus != StorageOperationStatus.OK) {
- log.debug("Failed to find capability of resource {}. status is {}", componentName, capStatus);
-
- }
- capStatus = setCompInstRequirementsFromGraph(compInstReq, component, compInstNodeType, compInst);
- if (capStatus != StorageOperationStatus.OK) {
- log.debug("Failed to find requirements of resource {}. status is {}", componentName, capStatus);
-
- }
-
- capStatus = setCompInstDeploymentArtifactsFromGraph(compInstDeploymentArtifacts, componentUid, compInst);
- if (capStatus != StorageOperationStatus.OK) {
- log.debug("Failed to find resource deployment artifacts of resource {}. status is {}", componentName, capStatus);
-
- }
-
- capStatus = setCompInstInformationalArtifactsResourceFromGraph(compInstInformationalArtifacts, componentUid, compInst);
- if (capStatus != StorageOperationStatus.OK) {
- log.debug("Failed to find resource deployment artifacts of resource {}. status is {}", componentName, capStatus);
-
- }
-
- capStatus = setCompInstDeploymentArtifactsFromGraph(compInst);
- if (capStatus != StorageOperationStatus.OK) {
- log.debug("Failed to find resource deployment artifacts of resource instance {} . status is {}", compInst.getName(), capStatus);
- }
-
- capStatus = setCompInstInformationaltArtifactsFromGraph(compInst);
- if (capStatus != StorageOperationStatus.OK) {
- log.debug("Failed to find resource informational artifacts of resource instance {} . status is {}", compInst.getName(), capStatus);
- }
-
- capStatus = setGroupInstFromGraph(compInst);
- if (capStatus != StorageOperationStatus.OK) {
- log.debug("Failed to find resource groups of resource instance {} . status is {}", compInst.getName(), capStatus);
- }
- return TitanOperationStatus.OK;
- }
-
- private StorageOperationStatus setCompInstInformationaltArtifactsFromGraph(ComponentInstance resourceInstance) {
- Map<String, ArtifactDefinition> informationalArtifacts = null;
- if (resourceInstance.getArtifacts() == null) {
- informationalArtifacts = new HashMap<String, ArtifactDefinition>();
- } else {
- informationalArtifacts = new HashMap<String, ArtifactDefinition>(resourceInstance.getArtifacts());
- }
-
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = artifactOperation.getArtifacts(resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true, ArtifactGroupTypeEnum.INFORMATIONAL.getType());
- if (result.isRight()) {
- StorageOperationStatus status = result.right().value();
- if (status != StorageOperationStatus.NOT_FOUND) {
- return status;
- }
- } else {
- informationalArtifacts.putAll(result.left().value());
- }
-
- resourceInstance.setArtifacts(informationalArtifacts);
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus setGroupInstFromGraph(ComponentInstance compInst) {
- List<GroupInstance> groupInstances = null;
-
- Either<List<GroupInstance>, StorageOperationStatus> result = groupInstanceOperation.getAllGroupInstances(compInst.getUniqueId(), NodeTypeEnum.ResourceInstance);
- if (result.isRight()) {
- StorageOperationStatus status = result.right().value();
- if (status != StorageOperationStatus.NOT_FOUND) {
- return status;
- } else {
-
- return StorageOperationStatus.OK;
- }
- }
-
- groupInstances = result.left().value();
- compInst.setGroupInstances(groupInstances);
-
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus setCompInstInformationalArtifactsResourceFromGraph(Map<String, Map<String, ArtifactDefinition>> resourcesInformationalArtifacts, String componentUid, ComponentInstance resourceInstance) {
-
- if (resourcesInformationalArtifacts.containsKey(componentUid)) {
- resourceInstance.setArtifacts(resourcesInformationalArtifacts.get(componentUid));
- return StorageOperationStatus.OK;
- }
-
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = artifactOperation.getArtifacts(componentUid, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.INFORMATIONAL.getType());
- if (result.isRight()) {
- StorageOperationStatus status = result.right().value();
- if (status != StorageOperationStatus.NOT_FOUND) {
- return status;
- } else {
- return StorageOperationStatus.OK;
- }
- }
- Map<String, ArtifactDefinition> artifacts = result.left().value();
- if (!artifacts.isEmpty()) {
- Map<String, ArtifactDefinition> tempArtifacts = new HashMap<>(artifacts);
- for (Entry<String, ArtifactDefinition> artifact : artifacts.entrySet()) {
- if (!artifact.getValue().checkEsIdExist()) {
- tempArtifacts.remove(artifact.getKey());
- }
- }
- resourceInstance.setArtifacts(tempArtifacts);
- resourcesInformationalArtifacts.put(componentUid, tempArtifacts);
- }
-
- return StorageOperationStatus.OK;
-
- }
-
- protected StorageOperationStatus setCompInstDeploymentArtifactsFromGraph(ComponentInstance resourceInstance) {
-
- Map<String, ArtifactDefinition> deploymentArtifacts = null;
- if (resourceInstance.getDeploymentArtifacts() == null) {
- deploymentArtifacts = new HashMap<String, ArtifactDefinition>();
- } else {
- deploymentArtifacts = new HashMap<String, ArtifactDefinition>(resourceInstance.getDeploymentArtifacts());
- }
-
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = artifactOperation.getArtifacts(resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
- if (result.isRight()) {
- StorageOperationStatus status = result.right().value();
- if (status != StorageOperationStatus.NOT_FOUND) {
- return status;
- } else {
- resourceInstance.setDeploymentArtifacts(deploymentArtifacts);
- return StorageOperationStatus.OK;
- }
- }
-
- Map<String, ArtifactDefinition> artifacts = result.left().value();
- if ((artifacts != null) && !artifacts.isEmpty()) {
- for (ArtifactDefinition artifact : artifacts.values()) {
- if (artifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
- Either<List<HeatParameterDefinition>, StorageOperationStatus> heatParamsForEnv = artifactOperation.getHeatParamsForEnv(artifact);
- if (heatParamsForEnv.isRight()) {
- log.debug("failed to get heat parameters values for heat artifact {}", artifact.getUniqueId());
- return heatParamsForEnv.right().value();
- } else {
- artifact.setListHeatParameters(heatParamsForEnv.left().value());
- }
- }
- }
-
- // add resource instance artifacts to the artifacts inherited from
- // resource
- deploymentArtifacts.putAll(artifacts);
- resourceInstance.setDeploymentArtifacts(deploymentArtifacts);
- }
-
- return StorageOperationStatus.OK;
-
- }
-
- private Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> getAllComponentInstanceFromGraph(String componentId, NodeTypeEnum containerNodeType, boolean withEdges) {
- if (log.isDebugEnabled())
- log.debug("Going to fetch all resource instances nodes in graph associate to component {}", componentId);
- Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> resourceInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(containerNodeType), componentId, GraphEdgeLabels.RESOURCE_INST,
- NodeTypeEnum.ResourceInstance, ComponentInstanceData.class, withEdges);
- if (log.isDebugEnabled())
- log.debug("After fetching all component instances under component {}", componentId);
-
- if (resourceInstancesRes.isLeft()) {
- printAllResourceInstancesNames(resourceInstancesRes);
- }
- return resourceInstancesRes;
- }
-
- private void printAllResourceInstancesNames(Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> resourceInstancesRes) {
- if (log.isTraceEnabled()) {
- StringBuilder builder = new StringBuilder();
- builder.append("Result is ");
- List<ImmutablePair<ComponentInstanceData, GraphEdge>> listResData = resourceInstancesRes.left().value();
- for (ImmutablePair<ComponentInstanceData, GraphEdge> resInstPair : listResData) {
- ComponentInstanceData resdata = resInstPair.getLeft();
- builder.append(resdata.getName()).append(", ");
- }
- log.trace(builder.toString());
- }
- }
-
- private TitanOperationStatus populateTargetAndRelationsForGivenSource(Map<String, List<ImmutablePair<String, RelationshipInstData>>> targetNodeToRelationship, List<ImmutablePair<RelationshipInstData, GraphEdge>> relationshipsImpl) {
- if (relationshipsImpl != null && false == relationshipsImpl.isEmpty()) {
- for (ImmutablePair<RelationshipInstData, GraphEdge> pair : relationshipsImpl) {
- RelationshipInstData relationshipInstData = pair.getKey();
-
- GraphEdge requirementEdge = pair.getValue();
- String requirementName = (String) requirementEdge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty());
-
- Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> targetNodeRes = titanGenericDao.getChild(relationshipInstData.getUniqueIdKey(), relationshipInstData.getUniqueId(), GraphEdgeLabels.CAPABILITY_NODE,
- NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
-
- if (targetNodeRes.isRight()) {
- TitanOperationStatus status = targetNodeRes.right().value();
- log.error("Failed to find the target node of relationship inst {}. status is {}", relationshipInstData, status);
- return status;
- }
-
- addRelationshipInstToTargetMap(targetNodeToRelationship, relationshipInstData, requirementName, targetNodeRes);
-
- }
- }
-
- return TitanOperationStatus.OK;
- }
-
- private TitanOperationStatus populateSourceAndRelationsForGivenTarget(Map<String, List<ImmutablePair<String, RelationshipInstData>>> sourceNodeToRelationship, List<ImmutablePair<RelationshipInstData, GraphEdge>> relationshipsImpl) {
- if (relationshipsImpl != null && false == relationshipsImpl.isEmpty()) {
- for (ImmutablePair<RelationshipInstData, GraphEdge> pair : relationshipsImpl) {
- RelationshipInstData relationshipInstData = pair.getKey();
-
- GraphEdge requirementEdge = pair.getValue();
- String requirementName = (String) requirementEdge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty());
-
- Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> sourceNodeRes = titanGenericDao.getParentNode(relationshipInstData.getUniqueIdKey(), relationshipInstData.getUniqueId(), GraphEdgeLabels.RELATIONSHIP_INST,
- NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
-
- if (sourceNodeRes.isRight()) {
- TitanOperationStatus status = sourceNodeRes.right().value();
- log.error("Failed to find the source node of relationship inst {}. status is {}", relationshipInstData, status);
- return status;
- }
-
- addRelationshipInstToTargetMap(sourceNodeToRelationship, relationshipInstData, requirementName, sourceNodeRes);
-
- }
- }
-
- return TitanOperationStatus.OK;
- }
-
- private void buildRelationsForSource(List<RequirementCapabilityRelDef> requirementsResult, String sourceResourceUid, Map<String, List<ImmutablePair<String, RelationshipInstData>>> targetNodeToRelationship) {
- for (Entry<String, List<ImmutablePair<String, RelationshipInstData>>> targetToRel : targetNodeToRelationship.entrySet()) {
- RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef();
- requirementCapabilityRelDef.setFromNode(sourceResourceUid);
- String targetUid = targetToRel.getKey();
- requirementCapabilityRelDef.setToNode(targetUid);
-
- List<RequirementAndRelationshipPair> relationships = new ArrayList<RequirementAndRelationshipPair>();
-
- populateRelationships(targetToRel, relationships);
- requirementCapabilityRelDef.setRelationships(relationships);
-
- requirementsResult.add(requirementCapabilityRelDef);
- }
- }
-
- private void buildRelationsForTarget(List<RequirementCapabilityRelDef> requirementsResult, String targetResourceUid, Map<String, List<ImmutablePair<String, RelationshipInstData>>> sourceNodeToRelationship) {
- for (Entry<String, List<ImmutablePair<String, RelationshipInstData>>> sourceToRel : sourceNodeToRelationship.entrySet()) {
- RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef();
- requirementCapabilityRelDef.setToNode(targetResourceUid);
- String sourceUid = sourceToRel.getKey();
- requirementCapabilityRelDef.setFromNode(sourceUid);
- List<RequirementAndRelationshipPair> relationships = new ArrayList<RequirementAndRelationshipPair>();
-
- populateRelationships(sourceToRel, relationships);
- requirementCapabilityRelDef.setRelationships(relationships);
-
- requirementsResult.add(requirementCapabilityRelDef);
- }
- }
-
- private void addRelationshipInstToTargetMap(Map<String, List<ImmutablePair<String, RelationshipInstData>>> targetNodeToRelationship, RelationshipInstData relationshipInstData, String requirementName,
- Either<ImmutablePair<ComponentInstanceData, GraphEdge>, TitanOperationStatus> targetNodeRes) {
-
- ImmutablePair<ComponentInstanceData, GraphEdge> targetResourcePair = targetNodeRes.left().value();
- ComponentInstanceData targetResourceData = targetResourcePair.getKey();
-
- GraphEdge edge = targetResourcePair.right;
- if (edge.getEdgeType().equals(GraphEdgeLabels.RELATIONSHIP_INST)) {
- requirementName = (String) edge.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty());
- }
-
- String targetResourceUid = (String) targetResourceData.getUniqueId();
- List<ImmutablePair<String, RelationshipInstData>> requirementRelationshipPair = targetNodeToRelationship.get(targetResourceUid);
- if (requirementRelationshipPair == null) {
- requirementRelationshipPair = new ArrayList<ImmutablePair<String, RelationshipInstData>>();
- targetNodeToRelationship.put(targetResourceUid, requirementRelationshipPair);
- }
- ImmutablePair<String, RelationshipInstData> reqRelationshipPair = new ImmutablePair<String, RelationshipInstData>(requirementName, relationshipInstData);
- requirementRelationshipPair.add(reqRelationshipPair);
- }
-
- private void populateRelationships(Entry<String, List<ImmutablePair<String, RelationshipInstData>>> targetToRel, List<RequirementAndRelationshipPair> relationships) {
-
- List<ImmutablePair<String, RelationshipInstData>> values = targetToRel.getValue();
- for (ImmutablePair<String, RelationshipInstData> value : values) {
- String reqName = value.getKey();
- RelationshipInstData relationshipInstData = value.getValue();
- RelationshipImpl relationshipImpl = new RelationshipImpl();
- relationshipImpl.setType(relationshipInstData.getType());
- RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair(reqName, relationshipImpl);
- pair.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId());
- pair.setCapabilityUid(relationshipInstData.getCapabiltyId());
- pair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId());
- pair.setRequirementUid(relationshipInstData.getRequirementId());
- pair.setId(relationshipInstData.getUniqueId());
- relationships.add(pair);
- }
- }
-
- /**
- * FOR TEST ONLY
- *
- * @param resourceOperation
- */
- public void setResourceOperation(ResourceOperation resourceOperation) {
- this.resourceOperation = resourceOperation;
- }
-
- @Override
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean inTransaction, boolean isClone) {
-
- Either<RequirementCapabilityRelDef, StorageOperationStatus> result = null;
- try {
- Either<RequirementCapabilityRelDef, TitanOperationStatus> multiRequirements = associateResourceInstancesMultiRequirements(componentId, nodeType, relation, isClone);
- if (multiRequirements.isRight()) {
- TitanOperationStatus status = multiRequirements.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "associateComponentInstances");
- BeEcompErrorManager.getInstance().logBeDaoSystemError("associateComponentInstances");
- log.debug("Failed to associate component instances {}. status is {}", relation, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- StorageOperationStatus updateCalculatedCapReqResult = updateCalculatedCapReq(relation, true);
- if (!updateCalculatedCapReqResult.equals(StorageOperationStatus.OK)) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "associateComponentInstances");
- BeEcompErrorManager.getInstance().logBeDaoSystemError("associateComponentInstances");
- log.debug("Failed to associate component instances. {}. status is {}", relation, updateCalculatedCapReqResult);
- result = Either.right(updateCalculatedCapReqResult);
- return result;
- }
- result = Either.left(multiRequirements.left().value());
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- commitOrRollback(result);
- }
- }
- }
-
- private Either<RequirementCapabilityRelDef, TitanOperationStatus> associateResourceInstancesMultiRequirements(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean isClone) {
-
- String fromNode = relation.getFromNode();
- String toNode = relation.getToNode();
- List<RequirementAndRelationshipPair> relationships = relation.getRelationships();
- if (relationships == null || relationships.isEmpty()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedAddingResourceInstanceError, "AssociateResourceInstances - missing relationship", fromNode, componentId);
- BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
- log.debug("No requirement definition sent in order to set the relation between {} to {}", fromNode, toNode);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
-
- List<RequirementAndRelationshipPair> relationshipsResult = new ArrayList<RequirementAndRelationshipPair>();
- for (RequirementAndRelationshipPair immutablePair : relationships) {
- String requirement = immutablePair.getRequirement();
-
- Either<RelationshipInstData, TitanOperationStatus> associateRes = connectResourcesInService(componentId, nodeType, fromNode, toNode, immutablePair);
-
- if (associateRes.isRight()) {
- TitanOperationStatus status = associateRes.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedAddingResourceInstanceError, "AssociateResourceInstances", fromNode, componentId);
- BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
- log.debug("Failed to associate resource instance {} to resource instance {}. status is {}", fromNode, toNode, status);
- return Either.right(status);
- }
-
- RelationshipInstData relationshipInstData = associateRes.left().value();
- RelationshipImpl relationshipImplResult = new RelationshipImpl();
- relationshipImplResult.setType(relationshipInstData.getType());
- RequirementAndRelationshipPair requirementAndRelationshipPair = new RequirementAndRelationshipPair(requirement, relationshipImplResult);
- requirementAndRelationshipPair.setCapability(immutablePair.getCapability());
- requirementAndRelationshipPair.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId());
- requirementAndRelationshipPair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId());
- requirementAndRelationshipPair.setCapabilityUid(immutablePair.getCapabilityUid());
- requirementAndRelationshipPair.setRequirementUid(immutablePair.getRequirementUid());
- relationshipsResult.add(requirementAndRelationshipPair);
- if (!isClone) {
- log.trace("update customization UUID for from CI {} and to CI {}", relation.getFromNode(), relation.getToNode());
- StorageOperationStatus status;
- status = updateCustomizationUUID(relation.getFromNode());
- if (status != StorageOperationStatus.OK) {
- return Either.right(TitanOperationStatus.GENERAL_ERROR);
- }
- status = updateCustomizationUUID(relation.getToNode());
- if (status != StorageOperationStatus.OK) {
- return Either.right(TitanOperationStatus.GENERAL_ERROR);
- }
- }
-
- }
-
- RequirementCapabilityRelDef capabilityRelDef = new RequirementCapabilityRelDef();
- capabilityRelDef.setFromNode(fromNode);
- capabilityRelDef.setToNode(toNode);
- capabilityRelDef.setRelationships(relationshipsResult);
-
- return Either.left(capabilityRelDef);
- }
-
- @Override
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation) {
- return associateResourceInstances(componentId, nodeType, relation, false, false);
- }
-
- @Override
- public Either<List<ComponentInstance>, StorageOperationStatus> deleteAllComponentInstances(String containerComponentId, NodeTypeEnum containerNodeType, boolean inTransaction) {
-
- Either<List<ComponentInstance>, StorageOperationStatus> result = null;
- try {
- Either<List<ComponentInstance>, TitanOperationStatus> multiRequirements = deleteAllComponentInstancesInternal(containerComponentId, containerNodeType);
- if (multiRequirements.isRight()) {
- TitanOperationStatus status = multiRequirements.right().value();
- if (multiRequirements.right().value() != TitanOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "deleteAllResourceInstances - missing relationship");
- BeEcompErrorManager.getInstance().logBeSystemError("deleteAllResourceInstances - missing relationship");
- }
- log.debug("Failed to delete resource instances of service {}. status is {}", containerComponentId, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
-
- }
-
- result = Either.left(multiRequirements.left().value());
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- commitOrRollback(result);
- }
- }
-
- }
-
- @Override
- public Either<List<ComponentInstance>, StorageOperationStatus> deleteAllComponentInstances(String containerComponentId, NodeTypeEnum nodeType) {
- return deleteAllComponentInstances(containerComponentId, nodeType, false);
- }
-
- public Either<List<ComponentInstance>, TitanOperationStatus> deleteAllComponentInstancesInternal(String componentId, NodeTypeEnum nodeType) {
-
- log.debug("Going to delete all resource instances and their relatioships from service {}", componentId);
-
- Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> resourceInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.RESOURCE_INST,
- NodeTypeEnum.ResourceInstance, ComponentInstanceData.class);
-
- if (resourceInstancesRes.isRight()) {
- TitanOperationStatus status = resourceInstancesRes.right().value();
- log.debug("After fetching all resource instances of service {}. status is {}", componentId, status);
- return Either.right(status);
- }
-
- List<ComponentInstance> result = new ArrayList<ComponentInstance>();
- List<ImmutablePair<ComponentInstanceData, GraphEdge>> listOfResInstances = resourceInstancesRes.left().value();
- for (ImmutablePair<ComponentInstanceData, GraphEdge> resInstance : listOfResInstances) {
- ComponentInstanceData resourceInstanceData = resInstance.getKey();
- String resourceInstUid = resourceInstanceData.getUniqueId();
- Either<ComponentInstance, TitanOperationStatus> removeResourceInstanceRes = removeComponentInstanceFromComponent(nodeType, componentId, resourceInstUid);
- log.debug("After removing resource instance {}. Result is {}", resourceInstUid, removeResourceInstanceRes);
- if (removeResourceInstanceRes.isRight()) {
- TitanOperationStatus status = removeResourceInstanceRes.right().value();
- log.error("After removing resource instance {}. status is {}", resourceInstUid, status);
- return Either.right(status);
- }
- ComponentInstance resourceInstance = removeResourceInstanceRes.left().value();
- result.add(resourceInstance);
- }
-
- log.debug("The following resource instances was deleted from service {} : {}", componentId, result);
-
- return Either.left(result);
- }
-
- public Either<ImmutablePair<List<ComponentInstance>, Map<String, String>>, StorageOperationStatus> cloneAllComponentInstancesFromContainerComponent(String componentIdFrom, Component component, NodeTypeEnum containerNodeType,
- NodeTypeEnum compInstNodeType, LifecycleStateEnum targetLifecycle, Map<String, List<ComponentInstanceInput>> inputsValuesMap) {
-
- List<ComponentInstance> list = new ArrayList<ComponentInstance>();
- Map<String, String> oldCompInstToNew = new HashMap<>();
-
- ImmutablePair<List<ComponentInstance>, Map<String, String>> result = new ImmutablePair<List<ComponentInstance>, Map<String, String>>(list, oldCompInstToNew);
-
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> allResourceInstances = getAllComponentInstances(componentIdFrom, containerNodeType, compInstNodeType, true);
-
- if (allResourceInstances.isRight()) {
- StorageOperationStatus status = allResourceInstances.right().value();
- if (status.equals(StorageOperationStatus.NOT_FOUND)) {
-
- return Either.left(result);
- } else {
- log.error("failed to get all resource instances for service {}. status={}", componentIdFrom, status);
- return Either.right(status);
- }
- }
-
- List<ComponentInstance> riList = allResourceInstances.left().value().left;
- Map<String, ComponentInstance> riMapper = new HashMap<>();
- int instanceNumber = 0;
- for (ComponentInstance ri : riList) {
- instanceNumber++;
- String origRiUniqueID = ri.getUniqueId();
- Either<ComponentInstance, StorageOperationStatus> createResourceInstance = createComponentInstance(component.getUniqueId(), containerNodeType, String.valueOf(instanceNumber), false, ri, compInstNodeType, true, true);
- if (createResourceInstance.isRight()) {
- StorageOperationStatus status = createResourceInstance.right().value();
- log.error("failed to clone resource instance {}. status ={}", origRiUniqueID, status);
- return Either.right(status);
- }
- ComponentInstance createdInstance = createResourceInstance.left().value();
- riMapper.put(origRiUniqueID, createdInstance);
- StorageOperationStatus associateArtifactsToResource = cloneResourceInstanceArtifacts(createdInstance, ri, targetLifecycle);
- if (associateArtifactsToResource != StorageOperationStatus.OK) {
- log.debug("failed to clone resource instance {} artifacts. error {} ", ri.getNormalizedName(), associateArtifactsToResource.name());
- return Either.right(associateArtifactsToResource);
- }
-
- StorageOperationStatus associatePropertyValuesToResource = cloneResourceInstancePropertyValues(createdInstance, ri);
- if (associatePropertyValuesToResource != StorageOperationStatus.OK) {
- log.debug("failed to clone resource instance {} property values. error {} ", ri.getNormalizedName(), associatePropertyValuesToResource.name());
- return Either.right(associatePropertyValuesToResource);
- }
-
- StorageOperationStatus associateAttributeValuesToResource = cloneResourceInstanceAttributeValues(createdInstance, ri);
- if (associateAttributeValuesToResource != StorageOperationStatus.OK) {
- log.debug("failed to clone resource instance {} attribute values. error {} ", ri.getNormalizedName(), associateAttributeValuesToResource.name());
- return Either.right(associateAttributeValuesToResource);
- }
-
- StorageOperationStatus associateInputValuesToResource = cloneResourceInstanceInputsValues(createdInstance, ri, component, inputsValuesMap);
- if (associateInputValuesToResource != StorageOperationStatus.OK) {
- log.debug("failed to clone resource instance {} property values. error {} ", ri.getNormalizedName(), associatePropertyValuesToResource.name());
- return Either.right(associatePropertyValuesToResource);
- }
-
- list.add(createdInstance);
- oldCompInstToNew.put(origRiUniqueID, createdInstance.getUniqueId());
- }
-
- List<RequirementCapabilityRelDef> relationsList = allResourceInstances.left().value().right;
- for (RequirementCapabilityRelDef relation : relationsList) {
- String origFrom = relation.getFromNode();
- String origTo = relation.getToNode();
- relation.setFromNode(riMapper.get(origFrom).getUniqueId());
- relation.setToNode(riMapper.get(origTo).getUniqueId());
- List<RequirementAndRelationshipPair> relationships = relation.getRelationships();
- for (RequirementAndRelationshipPair pair : relationships) {
- // for all atomic resource instances need to update to relevant
- // new ri ids
- String capOwnerId = pair.getCapabilityOwnerId();
- String reqOwnerId = pair.getRequirementOwnerId();
- if (isAtomicComponentInstance(riMapper.get(origFrom))) {
- reqOwnerId = riMapper.get(reqOwnerId).getUniqueId();
- }
- if (isAtomicComponentInstance(riMapper.get(origTo))) {
- capOwnerId = riMapper.get(capOwnerId).getUniqueId();
- }
- pair.setRequirementOwnerId(reqOwnerId);
- pair.setCapabilityOwnerId(capOwnerId);
- }
-
- Either<RequirementCapabilityRelDef, StorageOperationStatus> associateInstances = associateResourceInstances(component.getUniqueId(), containerNodeType, relation, true, true);
- if (associateInstances.isRight()) {
- StorageOperationStatus status = associateInstances.right().value();
- log.error("failed to assosiate resource instance {} and resource instance {}. status ={}", relation.getFromNode(), relation.getToNode(), status);
- return Either.right(status);
- }
- }
-
- return Either.left(result);
- }
-
- public Either<ImmutablePair<List<ComponentInstance>, Map<String, String>>, StorageOperationStatus> cloneAllComponentInstancesFromContainerComponent(String componentIdFrom, String componentIdTo, NodeTypeEnum containerNodeType,
- NodeTypeEnum compInstNodeType, LifecycleStateEnum targetLifecycle, TitanVertex metadataVertex, Resource prevResource, Resource newResource, Map<String, List<ComponentInstanceProperty>> inputsPropMap) {
-
- List<ComponentInstance> list = new ArrayList<ComponentInstance>();
- Map<String, String> oldCompInstToNew = new HashMap<>();
-
- ImmutablePair<List<ComponentInstance>, Map<String, String>> result = new ImmutablePair<List<ComponentInstance>, Map<String, String>>(list, oldCompInstToNew);
-
- List<ComponentInstance> riList = prevResource.getComponentInstances();
- Map<String, ComponentInstance> riMapper = new HashMap<>();
- int instanceNumber = 0;
- long timeProperties = 0;
- if (riList != null) {
- for (ComponentInstance ri : riList) {
- instanceNumber++;
- String origRiUniqueID = ri.getUniqueId();
- Either<TitanVertex, StorageOperationStatus> createResourceInstance = createComponentInstance(componentIdTo, containerNodeType, String.valueOf(instanceNumber), false, ri, compInstNodeType, true, true, metadataVertex);
- if (createResourceInstance.isRight()) {
- StorageOperationStatus status = createResourceInstance.right().value();
- log.error("failed to clone resource instance {}. status ={}", origRiUniqueID, status);
- return Either.right(status);
- }
- TitanVertex createdInstance = createResourceInstance.left().value();
- String createdInstanceId = (String) titanGenericDao.getProperty(createdInstance, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
-
- StorageOperationStatus associateArtifactsToResource = cloneResourceInstanceArtifacts(createdInstance, ri, targetLifecycle);
- if (associateArtifactsToResource != StorageOperationStatus.OK) {
- log.debug("failed to clone resource instance {} artifacts. error {} ", ri.getNormalizedName(), associateArtifactsToResource.name());
- return Either.right(associateArtifactsToResource);
- }
-
- long start = System.currentTimeMillis();
- StorageOperationStatus associatePropertyValuesToResource = cloneResourceInstancePropertyValues(createdInstance, ri, inputsPropMap, newResource);
- if (associatePropertyValuesToResource != StorageOperationStatus.OK) {
- log.debug("failed to clone resource instance {} property values. error {} ", ri.getNormalizedName(), associatePropertyValuesToResource.name());
- return Either.right(associatePropertyValuesToResource);
- }
- long end = System.currentTimeMillis();
- timeProperties += (end - start);
-
- StorageOperationStatus associateAttributeValuesToResource = cloneResourceInstanceAttributeValues(createdInstance, ri, createdInstanceId);
- if (associateAttributeValuesToResource != StorageOperationStatus.OK) {
- log.debug("failed to clone resource instance {} attribute values. error {} ", ri.getNormalizedName(), associateAttributeValuesToResource.name());
- return Either.right(associateAttributeValuesToResource);
- }
-
- StorageOperationStatus associateInputValuesToResource = cloneResourceInstanceInputsValues(createdInstance, ri, createdInstanceId, newResource, null);
- if (associateInputValuesToResource != StorageOperationStatus.OK) {
- log.debug("failed to clone resource instance {} property values. error {} ", ri.getNormalizedName(), associatePropertyValuesToResource.name());
- return Either.right(associatePropertyValuesToResource);
- }
- Map<String, Object> properties = titanGenericDao.getProperties(createdInstance);
- ComponentInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.ResourceInstance.getName(), GraphElementTypeEnum.Node, properties, ComponentInstanceData.class);
- ComponentInstance createdResourceInstance = new ComponentInstance(createdComponentInstance.getComponentInstDataDefinition());
- riMapper.put(origRiUniqueID, createdResourceInstance);
-
- list.add(createdResourceInstance);
- oldCompInstToNew.put(origRiUniqueID, createdResourceInstance.getUniqueId());
- }
- }
- log.info("*********** total properties in ms {}", timeProperties);
-
- // List<RequirementCapabilityRelDef> relationsList =
- // instanceRelationPair.right;
- List<RequirementCapabilityRelDef> relationsList = prevResource.getComponentInstancesRelations();
- if (relationsList != null) {
- for (RequirementCapabilityRelDef relation : relationsList) {
- String origFrom = relation.getFromNode();
- String origTo = relation.getToNode();
- relation.setFromNode(riMapper.get(origFrom).getUniqueId());
- relation.setToNode(riMapper.get(origTo).getUniqueId());
- List<RequirementAndRelationshipPair> relationships = relation.getRelationships();
- for (RequirementAndRelationshipPair pair : relationships) {
- // for all atomic resource instances need to update to
- // relevant
- // new ri ids
- String capOwnerId = pair.getCapabilityOwnerId();
- String reqOwnerId = pair.getRequirementOwnerId();
- if (isAtomicComponentInstance(riMapper.get(origFrom))) {
- reqOwnerId = riMapper.get(reqOwnerId).getUniqueId();
- }
- if (isAtomicComponentInstance(riMapper.get(origTo))) {
- capOwnerId = riMapper.get(capOwnerId).getUniqueId();
- }
- pair.setRequirementOwnerId(reqOwnerId);
- pair.setCapabilityOwnerId(capOwnerId);
- }
-
- Either<RequirementCapabilityRelDef, StorageOperationStatus> associateInstances = associateResourceInstances(componentIdTo, containerNodeType, relation, true, true);
- if (associateInstances.isRight()) {
- StorageOperationStatus status = associateInstances.right().value();
- log.error("failed to assosiate resource instance {} and resource instance {}. status ={}", relation.getFromNode(), relation.getToNode(), status);
- return Either.right(status);
- }
- }
- }
- return Either.left(result);
- }
-
- private boolean isAtomicComponentInstance(ComponentInstance componentInstance) {
- OriginTypeEnum originType = componentInstance.getOriginType();
- if (originType == OriginTypeEnum.VFC || originType == OriginTypeEnum.VFCMT || originType == OriginTypeEnum.VL || originType == OriginTypeEnum.CP) {
- return true;
- }
- return false;
- }
-
- private StorageOperationStatus cloneResourceInstanceArtifacts(ComponentInstance toResourceInstance, ComponentInstance fromResourceInstance, LifecycleStateEnum targetLifecycle) {
-
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsOfRI = artifactOperation.getArtifacts(fromResourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true);
- if (getArtifactsOfRI.isRight()) {
- StorageOperationStatus status = getArtifactsOfRI.right().value();
- if (status.equals(StorageOperationStatus.NOT_FOUND)) {
- status = StorageOperationStatus.OK;
- }
- return status;
- }
-
- Map<String, ArtifactDefinition> artifacts = getArtifactsOfRI.left().value();
- List<GroupInstance> groupInstancesFrom = fromResourceInstance.getGroupInstances();
- List<GroupInstance> groupInstancesTo = toResourceInstance.getGroupInstances();
- Map<String, List<String>> groupsInstanceArtifact = new HashMap<String, List<String>>();
- for (Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
-
- ArtifactDefinition artifactDefinition = entry.getValue();
- String generatedFromIdArtifactUid = artifactDefinition.getGeneratedFromId();
-
- // US687135 Do not Add VF_MODULES_METADATA when checking out
- if (ArtifactTypeEnum.VF_MODULES_METADATA.getType().equals(artifactDefinition.getArtifactType())) {
- // The artifact of type VF_MODULES_METADATA should not be cloned
- // unless we are changing the state to certified.
- if (targetLifecycle != null && targetLifecycle != LifecycleStateEnum.CERTIFIED) {
- continue;
- }
- }
- Either<ArtifactDefinition, StorageOperationStatus> addArifactToResource = Either.left(artifactDefinition);
-
- addArifactToResource = artifactOperation.addArifactToComponent(artifactDefinition, toResourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, false, true);
-
- if (addArifactToResource.isRight()) {
- return addArifactToResource.right().value();
- }
-
- if (groupInstancesTo != null) {
- for (GroupInstance groupInstanceTo : groupInstancesTo) {
- Optional<String> op = groupInstanceTo.getArtifacts().stream().filter(p -> p.equals(generatedFromIdArtifactUid)).findAny();
- if (op.isPresent()) {
-
- List<String> artifactsUid = null;
- if (groupsInstanceArtifact.containsKey(groupInstanceTo.getUniqueId())) {
- artifactsUid = groupsInstanceArtifact.get(groupInstanceTo.getUniqueId());
- } else {
- artifactsUid = new ArrayList<String>();
- }
- artifactsUid.add(addArifactToResource.left().value().getUniqueId());
- groupsInstanceArtifact.put(groupInstanceTo.getUniqueId(), artifactsUid);
- break;
- }
- }
-
- }
- }
- if (groupsInstanceArtifact != null && !groupsInstanceArtifact.isEmpty()) {
- for (Map.Entry<String, List<String>> groupArtifact : groupsInstanceArtifact.entrySet()) {
- groupInstanceOperation.associateArtifactsToGroupInstance(groupArtifact.getKey(), groupArtifact.getValue());
- }
- }
- Either<List<GroupInstance>, StorageOperationStatus> groupInstanceStatus = groupInstanceOperation.getAllGroupInstances(toResourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance);
- if (groupInstanceStatus.isRight()) {
- log.debug("failed to get groupinstance for component inatance {}", toResourceInstance.getUniqueId());
- return groupInstanceStatus.right().value();
- }
- toResourceInstance.setGroupInstances(groupInstanceStatus.left().value());
- toResourceInstance.setDeploymentArtifacts(artifacts);
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus cloneResourceInstanceArtifacts(TitanVertex toResourceInstance, ComponentInstance fromResourceInstance, LifecycleStateEnum targetLifecycle) {
-
- Either<Map<String, TitanVertex>, StorageOperationStatus> getArtifactsOfRI = artifactOperation.getArtifactsVertecies(fromResourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true);
- if (getArtifactsOfRI.isRight()) {
- StorageOperationStatus status = getArtifactsOfRI.right().value();
- if (status.equals(StorageOperationStatus.NOT_FOUND)) {
- status = StorageOperationStatus.OK;
- }
- return status;
- }
-
- Map<String, TitanVertex> artifacts = getArtifactsOfRI.left().value();
- for (Entry<String, TitanVertex> entry : artifacts.entrySet()) {
-
- TitanVertex artifactVertex = entry.getValue();
- // US687135 Do not Add VF_MODULES_METADATA when checking out
- String artifactType = (String) titanGenericDao.getProperty(artifactVertex, GraphPropertiesDictionary.ARTIFACT_TYPE.getProperty());
- String label = (String) titanGenericDao.getProperty(artifactVertex, GraphPropertiesDictionary.ARTIFACT_LABEL.getProperty());
- if (ArtifactTypeEnum.VF_MODULES_METADATA.getType().equals(artifactType)) {
- // The artifact of type VF_MODULES_METADATA should not be cloned
- // unless we are changing the state to certified.
- if (targetLifecycle != null && targetLifecycle != LifecycleStateEnum.CERTIFIED) {
- continue;
- }
- }
-
- StorageOperationStatus addArifactToResource = artifactOperation.addArifactToComponent(artifactVertex, toResourceInstance, label);
-
- if (!addArifactToResource.equals(StorageOperationStatus.OK)) {
- return addArifactToResource;
- }
- }
- // toResourceInstance.setDeploymentArtifacts(artifacts);
- return StorageOperationStatus.OK;
- }
-
public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction) {
Either<Integer, StorageOperationStatus> result = null;
@@ -3566,449 +145,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
- public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter(TitanVertex resourceInstanceVertex, GraphPropertiesDictionary counterType) {
-
- Either<Integer, StorageOperationStatus> result = null;
-
- VertexProperty<Object> vertexProperty = resourceInstanceVertex.property(counterType.getProperty());
- Integer counter = 0;
- if (vertexProperty.isPresent()) {
- if (vertexProperty.value() != null) {
- counter = (Integer) vertexProperty.value();
- }
- }
- counter++;
- resourceInstanceVertex.property(counterType.getProperty(), counter);
-
- result = Either.left(counter);
- return result;
-
- }
-
- @Override
- public Either<List<String>, StorageOperationStatus> getAllComponentInstancesNames(String serviceId, NodeTypeEnum nodeType, boolean inTransaction) {
-
- Either<List<String>, StorageOperationStatus> result = null;
-
- try {
-
- Either<List<String>, TitanOperationStatus> resInstancesOfService = getComponentInstancesNameOfService(serviceId, nodeType);
-
- log.debug("After fetching resource instances of service {}. result is {}", serviceId, resInstancesOfService);
- if (resInstancesOfService.isRight()) {
- TitanOperationStatus status = resInstancesOfService.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find resource instances of service {}. status is {}", serviceId, status);
- }
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- List<String> names = resInstancesOfService.left().value();
-
- if (names == null || names.isEmpty()) {
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
-
- result = Either.left(names);
-
- } finally {
- if (false == inTransaction) {
- commitOrRollback(result);
- }
- }
- return result;
- }
-
- private Either<List<String>, TitanOperationStatus> getComponentInstancesNameOfService(String serviceId, NodeTypeEnum nodeType) {
-
- List<String> resourcesInstanseName = new ArrayList<String>();
- Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> resourceInstancesRes = getAllComponentInstanceFromGraph(serviceId, nodeType, false);
- if (resourceInstancesRes.isRight()) {
- TitanOperationStatus status = resourceInstancesRes.right().value();
- log.debug("Resource instance was found under service {}. status is {}", serviceId, status);
- return Either.right(status);
- }
-
- List<ImmutablePair<ComponentInstanceData, GraphEdge>> resourceInstances = resourceInstancesRes.left().value();
- if (resourceInstances != null && false == resourceInstances.isEmpty()) {
-
- for (ImmutablePair<ComponentInstanceData, GraphEdge> immutablePair : resourceInstances) {
- ComponentInstanceData resourceInstanceData = immutablePair.getKey();
- log.debug("Going to fetch the relationships of resource instance {}", resourceInstanceData);
- resourcesInstanseName.add(resourceInstanceData.getComponentInstDataDefinition().getName());
-
- }
- }
-
- return Either.left(resourcesInstanseName);
- }
-
- @Override
- public Either<List<String>, StorageOperationStatus> getAllComponentInstancesNames(String componentId, NodeTypeEnum nodeType) {
-
- return getAllComponentInstancesNames(componentId, nodeType, false);
- }
-
- @Override
- public Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(String resourceId) {
- Either<ComponentInstanceData, TitanOperationStatus> resourceInstanceData = findResourceInstance(resourceId);
-
- if (resourceInstanceData.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceInstanceData.right().value()));
- }
-
- return Either.left(new ComponentInstance(resourceInstanceData.left().value().getComponentInstDataDefinition()));
-
- }
-
- private StorageOperationStatus setCompInstDeploymentArtifactsFromGraph(Map<String, Map<String, ArtifactDefinition>> resourcesArtifacts, String uniqueId, ComponentInstance resourceInstance) {
-
- if (resourcesArtifacts.containsKey(uniqueId)) {
- resourceInstance.setDeploymentArtifacts(resourcesArtifacts.get(uniqueId));
- return StorageOperationStatus.OK;
- }
-
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = artifactOperation.getArtifacts(uniqueId, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
- if (result.isRight()) {
- StorageOperationStatus status = result.right().value();
- if (status != StorageOperationStatus.NOT_FOUND) {
- return status;
- } else {
- return StorageOperationStatus.OK;
- }
- }
- Map<String, ArtifactDefinition> artifacts = result.left().value();
- if (!artifacts.isEmpty()) {
- Map<String, ArtifactDefinition> tempArtifacts = new HashMap<String, ArtifactDefinition>(artifacts);
- for (Entry<String, ArtifactDefinition> artifact : artifacts.entrySet()) {
- if (!artifact.getValue().checkEsIdExist()) {
- tempArtifacts.remove(artifact.getKey());
- }
- }
- resourceInstance.setDeploymentArtifacts(tempArtifacts);
- resourcesArtifacts.put(uniqueId, tempArtifacts);
- }
-
- return StorageOperationStatus.OK;
-
- }
-
- private StorageOperationStatus setCompInstCapabilitiesFromGraph(Map<String, Map<String, CapabilityDefinition>> resourcesCapabilities, Component component, NodeTypeEnum compInstType, ComponentInstance resourceInstance,
- List<String> respourceDerivedList) {
-
- StorageOperationStatus status;
- ComponentOperation componentOperation = getComponentOperation(compInstType);
- Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> eitherCapabilities = componentOperation.getCapabilities(component, compInstType, true);
- if (eitherCapabilities.isLeft()) {
- status = StorageOperationStatus.OK;
- Map<String, List<CapabilityDefinition>> capabilities = eitherCapabilities.left().value();
- if (capabilities != null && !capabilities.isEmpty()) {
- capabilities.forEach((type, list) -> {
- if (list != null && !list.isEmpty()) {
- list.forEach((capability) -> {
- // We want to set ownerId only for instances coming
- // from atomic resources, otherwise we don't want
- // to overwrite the existing ownerId of underlying
- // component instances
- if (isAtomicResource(component)) {
- capability.setOwnerId(resourceInstance.getUniqueId());
- capability.setOwnerName(resourceInstance.getName());
- capability.setCapabilitySources(respourceDerivedList);
- }
- });
- }
- });
- resourceInstance.setCapabilities(capabilities);
- }
- } else {
- status = StorageOperationStatus.GENERAL_ERROR;
- }
- return status;
-
- }
-
- private StorageOperationStatus setCompInstRequirementsFromGraph(Map<String, Map<String, RequirementDefinition>> resourcesReq, Component component, NodeTypeEnum compInstType, ComponentInstance resourceInstance) {
- StorageOperationStatus status;
- ComponentOperation componentOperation = getComponentOperation(compInstType);
- Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> eitherCapabilities = componentOperation.getRequirements(component, compInstType, true);
- if (eitherCapabilities.isLeft()) {
- status = StorageOperationStatus.OK;
- Map<String, List<RequirementDefinition>> requirements = eitherCapabilities.left().value();
- if (requirements != null && !requirements.isEmpty()) {
- // We want to set ownerId only for instances coming from atomic
- // resources, otherwise we don't want
- // to overwrite the existing ownerId of underlying component
- // instances
- if (isAtomicResource(component)) {
- requirements.forEach((type, list) -> {
- if (list != null && !list.isEmpty()) {
- list.forEach((requirement) -> {
- requirement.setOwnerId(resourceInstance.getUniqueId());
- requirement.setOwnerName(resourceInstance.getName());
- });
- }
- });
- }
- resourceInstance.setRequirements(requirements);
- }
- } else {
- status = StorageOperationStatus.GENERAL_ERROR;
- }
- return status;
- }
-
- @Override
- public Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) {
- DataNodeCollector<CapabilityData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability,
- CapabilityData.class);
-
- return getDataFromGraph(collector);
- }
-
- @Override
- public Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) {
-
- DataNodeCollector<RequirementData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_REQUIREMENT, NodeTypeEnum.Requirement,
- RequirementData.class);
-
- return getDataFromGraph(collector);
-
- }
-
- @Override
- public Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getFulfilledCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) {
- DataNodeCollector<CapabilityData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_CAPABILITY_FULLFILLED, NodeTypeEnum.Capability,
- CapabilityData.class);
-
- return getDataFromGraph(collector);
- }
-
- @Override
- public Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getFulfilledRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) {
-
- DataNodeCollector<RequirementData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED, NodeTypeEnum.Requirement,
- RequirementData.class);
-
- return getDataFromGraph(collector);
-
- }
-
- public Either<Boolean, StorageOperationStatus> isAvailableRequirement(ComponentInstance fromResInstance, RequirementAndRelationshipPair relationPair) {
- Either<TitanVertex, TitanOperationStatus> fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstance.getUniqueId());
- if (fromRi.isRight()) {
- log.debug("Failed to fetch component instance {} error {}", fromResInstance.getUniqueId(), fromRi.right().value());
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- Iterator<Edge> edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_REQUIREMENT.name());
- if (edgeIter == null || !edgeIter.hasNext()) {
- log.debug("No available CALCULATED_REQUIREMENT edges. All full filled for RI {}", fromResInstance.getUniqueId());
- return Either.left(false);
- }
- boolean exist = false;
- while (edgeIter.hasNext()) {
- Edge edge = edgeIter.next();
- TitanVertex reqVertex = (TitanVertex) edge.inVertex();
- String reqId = (String) titanGenericDao.getProperty(reqVertex, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement));
- if (reqId.equals(relationPair.getRequirementUid())) {
- String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
- if (ownerIdOnEdge.equals(relationPair.getRequirementOwnerId())) {
- String leftOccurrences = (String) edge.value(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
- if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
- Integer leftIntValue = Integer.parseInt(leftOccurrences);
- if (leftIntValue > 0) {
- exist = true;
- }
- } else {
- exist = true;
- }
- break;
- }
- }
- }
- return Either.left(exist);
- }
-
- public Either<Boolean, StorageOperationStatus> isAvailableCapabilty(ComponentInstance toResInstance, RequirementAndRelationshipPair relationPair) {
- Either<TitanVertex, TitanOperationStatus> fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), toResInstance.getUniqueId());
- if (fromRi.isRight()) {
- log.debug("Failed to fetch component instance {} error {}", toResInstance.getUniqueId(), fromRi.right().value());
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- Iterator<Edge> edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_CAPABILITY.name());
- if (edgeIter == null || !edgeIter.hasNext()) {
- log.debug("No available CALCULATED_CAPABILITY edges. All full filled for RI {}", toResInstance.getUniqueId());
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- boolean exist = false;
- while (edgeIter.hasNext()) {
- Edge edge = edgeIter.next();
- TitanVertex reqVertex = (TitanVertex) edge.inVertex();
- String capId = (String) titanGenericDao.getProperty(reqVertex, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability));
- if (capId.equals(relationPair.getCapabilityUid())) {
- String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
- if (ownerIdOnEdge.equals(relationPair.getCapabilityOwnerId())) {
- String leftOccurrences = (String) edge.value(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
- if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
- Integer leftIntValue = Integer.parseInt(leftOccurrences);
- if (leftIntValue > 0) {
- exist = true;
- }
- } else {
- exist = true;
- }
- break;
- }
- }
- }
- return Either.left(exist);
- }
-
- interface DataNodeCollector<Data> {
- Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus> getDataNodes();
- }
-
- public <Data> Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus> getDataFromGraph(DataNodeCollector<Data> dataCollector) {
- Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus> eitherRet;
-
- Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus> childrenNodes = dataCollector.getDataNodes();
-
- if (childrenNodes.isLeft()) {
- List<ImmutablePair<Data, GraphEdge>> collectedData = childrenNodes.left().value().stream().map(element -> new ImmutablePair<Data, GraphEdge>(element.getLeft(), element.getRight())).collect(Collectors.toList());
- eitherRet = Either.left(collectedData);
- } else {
- eitherRet = Either.right(childrenNodes.right().value());
- }
- return eitherRet;
- }
-
- public ComponentOperation getComponentOperation(NodeTypeEnum componentType) {
- if (NodeTypeEnum.Service == componentType) {
- return serviceOperation;
- } else if (NodeTypeEnum.Resource == componentType) {
- return resourceOperation;
- }
- return null;
- }
-
- private boolean isAtomicResource(Component component) {
- // true if component is of type VL/CP/VFC
- boolean isFromAtomicResource = (component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() != ResourceTypeEnum.VF);
- return isFromAtomicResource;
- }
-
- private StorageOperationStatus cloneResourceInstanceAttributeValues(ComponentInstance createdInstance, ComponentInstance resourceInstance) {
- Wrapper<StorageOperationStatus> storageStatusWrapper = new Wrapper<>();
- Wrapper<List<ComponentInstanceProperty>> compInstanceAttList = new Wrapper<>();
-
- findAllAttributesOfResourceInstance(resourceInstance, compInstanceAttList, storageStatusWrapper);
-
- if (storageStatusWrapper.isEmpty()) {
- validateListNotEmpty(storageStatusWrapper, compInstanceAttList.getInnerElement());
- }
-
- if (storageStatusWrapper.isEmpty()) {
- List<ComponentInstanceProperty> attributesOnInstance = compInstanceAttList.getInnerElement();
- for (int i = 0; i < attributesOnInstance.size() && storageStatusWrapper.isEmpty(); i++) {
- cloneSingleAttributeOnResourceInstance(createdInstance, attributesOnInstance.get(i), storageStatusWrapper);
- }
- }
-
- StorageOperationStatus result = storageStatusWrapper.isEmpty() ? StorageOperationStatus.OK : storageStatusWrapper.getInnerElement();
- return result;
-
- }
-
- private StorageOperationStatus cloneResourceInstanceAttributeValues(TitanVertex createdInstanceVertex, ComponentInstance resourceInstance, String instanceId) {
- Wrapper<StorageOperationStatus> storageStatusWrapper = new Wrapper<>();
- Wrapper<List<ComponentInstanceProperty>> compInstanceAttList = new Wrapper<>();
-
- findAllAttributesOfResourceInstance(resourceInstance, compInstanceAttList, storageStatusWrapper);
-
- if (storageStatusWrapper.isEmpty()) {
- validateListNotEmpty(storageStatusWrapper, compInstanceAttList.getInnerElement());
- }
-
- if (storageStatusWrapper.isEmpty()) {
- List<ComponentInstanceProperty> attributesOnInstance = compInstanceAttList.getInnerElement();
- for (int i = 0; i < attributesOnInstance.size() && storageStatusWrapper.isEmpty(); i++) {
- StorageOperationStatus result = cloneSingleAttributeOnResourceInstance(createdInstanceVertex, attributesOnInstance.get(i), instanceId);
- if (result != StorageOperationStatus.OK) {
- log.trace("Failed to clone attribute for instance {} error {}", instanceId, result);
- return result;
- }
- }
- }
-
- StorageOperationStatus result = storageStatusWrapper.isEmpty() ? StorageOperationStatus.OK : storageStatusWrapper.getInnerElement();
- return result;
-
- }
-
- private <T> void validateListNotEmpty(Wrapper<StorageOperationStatus> storageStatusWrapper, List<T> attributesOnInstance) {
- if (attributesOnInstance == null || attributesOnInstance.isEmpty() == true) {
- storageStatusWrapper.setInnerElement(StorageOperationStatus.OK);
- }
- }
-
- private void findAllAttributesOfResourceInstance(ComponentInstance resourceInstance, Wrapper<List<ComponentInstanceProperty>> compInstanceAttList, Wrapper<StorageOperationStatus> storageStatusWrapper) {
-
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> allAttributes = attributeOperation.getAllAttributesOfResourceInstance(resourceInstance);
- if (allAttributes.isRight()) {
- TitanOperationStatus status = allAttributes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.OK;
- }
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- storageStatusWrapper.setInnerElement(storageStatus);
- } else {
- compInstanceAttList.setInnerElement(allAttributes.left().value());
- }
- }
-
- private void cloneSingleAttributeOnResourceInstance(ComponentInstance createdInstance, ComponentInstanceProperty attribute, Wrapper<StorageOperationStatus> storageStatusWrapper) {
- // Only if valueUniqueId is not empty, then its belongs to the
- // instance
- if (attribute.getValueUniqueUid() != null) {
- attribute.setValueUniqueUid(null);
- Either<Integer, StorageOperationStatus> counterRes = increaseAndGetResourceInstanceSpecificCounter(createdInstance.getUniqueId(), GraphPropertiesDictionary.ATTRIBUTE_COUNTER, true);
- if (counterRes.isRight()) {
- storageStatusWrapper.setInnerElement(counterRes.right().value());
- } else {
- Either<AttributeValueData, TitanOperationStatus> addAttributeToResourceInstance = addAttributeToResourceInstance(attribute, createdInstance.getUniqueId(), counterRes.left().value());
-
- if (addAttributeToResourceInstance.isRight()) {
- TitanOperationStatus status = addAttributeToResourceInstance.right().value();
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- storageStatusWrapper.setInnerElement(storageStatus);
- }
- }
- }
-
- }
-
- private StorageOperationStatus cloneSingleAttributeOnResourceInstance(TitanVertex createdInstanceVertex, ComponentInstanceProperty attribute, String instanceId) {
- // Only if valueUniqueId is not empty, then its belongs to the
- // instance
- if (attribute.getValueUniqueUid() != null) {
- attribute.setValueUniqueUid(null);
- Either<Integer, StorageOperationStatus> counterRes = increaseAndGetResourceInstanceSpecificCounter(createdInstanceVertex, GraphPropertiesDictionary.ATTRIBUTE_COUNTER);
- if (counterRes.isRight()) {
- return counterRes.right().value();
- } else {
- Either<AttributeValueData, TitanOperationStatus> addAttributeToResourceInstance = addAttributeToResourceInstance(attribute, instanceId, counterRes.left().value());
-
- if (addAttributeToResourceInstance.isRight()) {
- TitanOperationStatus status = addAttributeToResourceInstance.right().value();
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- return storageStatus;
- }
- }
- }
- return StorageOperationStatus.OK;
-
- }
-
private void connectAttValueDataToComponentInstanceData(Wrapper<TitanOperationStatus> errorWrapper, ComponentInstanceData compIns, AttributeValueData attValueData) {
Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(compIns, attValueData, GraphEdgeLabels.ATTRIBUTE_VALUE, null);
@@ -4021,18 +157,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
}
- private void connectInputValueDataToComponentInstanceData(Wrapper<TitanOperationStatus> errorWrapper, ComponentInstanceData compIns, InputValueData attValueData) {
-
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(compIns, attValueData, GraphEdgeLabels.INPUT_VALUE, null);
-
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createRelResult.right().value();
- errorWrapper.setInnerElement(operationStatus);
- BeEcompErrorManager.getInstance().logInternalFlowError("connectInputValueDataToComponentInstanceData",
- "Failed to associate resource instance " + compIns.getUniqueId() + " input value " + attValueData.getUniqueId() + " in graph. status is " + operationStatus, ErrorSeverity.ERROR);
- }
- }
-
private void connectAttValueDataToAttData(Wrapper<TitanOperationStatus> errorWrapper, AttributeData attData, AttributeValueData attValueData) {
Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(attValueData, attData, GraphEdgeLabels.ATTRIBUTE_IMPL, null);
@@ -4046,19 +170,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
}
- private void connectInputValueDataToInputData(Wrapper<TitanOperationStatus> errorWrapper, InputsData attData, InputValueData attValueData) {
-
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(attValueData, attData, GraphEdgeLabels.INPUT_IMPL, null);
-
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createRelResult.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("connectInputValueDataToInputData", "Failed to associate input value " + attValueData.getUniqueId() + " to input " + attData.getUniqueId() + " in graph. status is " + operationStatus,
- ErrorSeverity.ERROR);
-
- errorWrapper.setInnerElement(operationStatus);
- }
- }
-
private void createAttributeValueDataNode(ComponentInstanceProperty attributeInstanceProperty, Integer index, Wrapper<TitanOperationStatus> errorWrapper, ComponentInstanceData resourceInstanceData,
Wrapper<AttributeValueData> attValueDataWrapper) {
String valueUniqueUid = attributeInstanceProperty.getValueUniqueUid();
@@ -4084,21 +195,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
}
- /*
- * private void createInputValueDataNode(ComponentInstanceInput inputInstanceProperty, Integer index, Wrapper<TitanOperationStatus> errorWrapper, ComponentInstanceData resourceInstanceData, Wrapper<AttributeValueData> attValueDataWrapper) {
- * String valueUniqueUid = inputInstanceProperty.getValueUniqueUid(); if (valueUniqueUid == null) {
- *
- * String attValueDatauniqueId = UniqueIdBuilder.buildResourceInstanceInputValueUid(resourceInstanceData. getUniqueId(), index); AttributeValueData attributeValueData = buildAttributeValueDataFromComponentInstanceAttribute( inputInstanceProperty,
- * attValueDatauniqueId);
- *
- * log.debug("Before adding attribute value to graph {}", attributeValueData); Either<AttributeValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(attributeValueData, AttributeValueData.class);
- * log.debug("After adding attribute value to graph {}", attributeValueData);
- *
- * if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); errorWrapper.setInnerElement(operationStatus); } else { attValueDataWrapper.setInnerElement(createNodeResult.left().value()); }
- *
- * } else { BeEcompErrorManager.getInstance().logInternalFlowError( "CreateAttributeValueDataNode", "attribute value already exists.", ErrorSeverity.ERROR); errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST); } }
- */
-
private AttributeValueData buildAttributeValueDataFromComponentInstanceAttribute(ComponentInstanceProperty resourceInstanceAttribute, String uniqueId) {
AttributeValueData attributeValueData = new AttributeValueData();
attributeValueData.setUniqueId(uniqueId);
@@ -4111,360 +207,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
return attributeValueData;
}
- private InputValueData buildAttributeValueDataFromComponentInstanceAttribute(ComponentInstanceInput resourceInstanceInput, String uniqueId) {
- InputValueData inputValueData = new InputValueData();
- inputValueData.setUniqueId(uniqueId);
- inputValueData.setHidden(resourceInstanceInput.isHidden());
- inputValueData.setValue(resourceInstanceInput.getValue());
- inputValueData.setType(resourceInstanceInput.getType());
- long currentTimeMillis = System.currentTimeMillis();
- inputValueData.setCreationTime(currentTimeMillis);
- inputValueData.setModificationTime(currentTimeMillis);
- return inputValueData;
- }
-
- private StorageOperationStatus cloneResourceInstancePropertyValues(ComponentInstance toResourceInstance, ComponentInstance fromResourceInstance) {
-
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> allProperties = propertyOperation.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(fromResourceInstance.getUniqueId());
- if (allProperties.isRight()) {
- TitanOperationStatus status = allProperties.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.OK;
- }
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- return storageStatus;
- }
-
- List<ComponentInstanceProperty> propertiesOnInstance = allProperties.left().value();
- if (propertiesOnInstance == null || propertiesOnInstance.isEmpty() == true) {
- return StorageOperationStatus.OK;
- }
-
- for (ComponentInstanceProperty property : propertiesOnInstance) {
-
- // Only if valueUniqueId is not empty, then its belongs to the
- // instance
- if (property.getValueUniqueUid() != null) {
- property.setValueUniqueUid(null);
- List<PropertyRule> rules = property.getRules();
- if (rules != null) {
- for (PropertyRule propertyRule : rules) {
- propertyRule.replaceFirstToken(toResourceInstance.getUniqueId());
- }
- }
-
- } else {
- continue;
- }
-
- String resourceInstanceId = toResourceInstance.getUniqueId();
-
- Either<Integer, StorageOperationStatus> counterRes = this.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.PROPERTY_COUNTER, true);
-
- if (counterRes.isRight()) {
- log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property);
- StorageOperationStatus status = counterRes.right().value();
- return status;
- }
- Integer index = counterRes.left().value();
-
- Either<PropertyValueData, TitanOperationStatus> addPropertyToResourceInstance = this.addPropertyToResourceInstance(property, toResourceInstance.getUniqueId(), false, index);
-
- if (addPropertyToResourceInstance.isRight()) {
- TitanOperationStatus status = addPropertyToResourceInstance.right().value();
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- return storageStatus;
- }
- }
-
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus cloneResourceInstancePropertyValues(TitanVertex toResourceInstance, ComponentInstance fromResourceInstance, Map<String, List<ComponentInstanceProperty>> inputsPropMap, Resource newResource) {
-
- String riId = (String) titanGenericDao.getProperty(toResourceInstance, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> allProperties = propertyOperation.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(fromResourceInstance.getUniqueId());
- List<InputDefinition> newInputs = newResource.getInputs();
- //
- if (allProperties.isRight()) {
- TitanOperationStatus status = allProperties.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.OK;
- }
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- return storageStatus;
- }
-
- List<ComponentInstanceProperty> propertiesOnInstance = allProperties.left().value();
- if (propertiesOnInstance == null || propertiesOnInstance.isEmpty() == true) {
- return StorageOperationStatus.OK;
- }
-
- for (ComponentInstanceProperty property : propertiesOnInstance) {
-
- // Only if valueUniqueId is not empty, then its belongs to the
- // instance
- if (property.getValueUniqueUid() != null) {
- property.setValueUniqueUid(null);
- List<PropertyRule> rules = property.getRules();
- if (rules != null) {
- for (PropertyRule propertyRule : rules) {
- propertyRule.replaceFirstToken(riId);
- }
- }
-
- } else {
- continue;
- }
-
- String resourceInstanceId = riId;
-
- Either<Integer, StorageOperationStatus> counterRes = this.increaseAndGetResourceInstanceSpecificCounter(toResourceInstance, GraphPropertiesDictionary.PROPERTY_COUNTER);
-
- if (counterRes.isRight()) {
- log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property);
- StorageOperationStatus status = counterRes.right().value();
- return status;
- }
- Integer index = counterRes.left().value();
-
- Either<ComponentInstanceProperty, TitanOperationStatus> addPropertyToResourceInstance = this.addPropertyToResourceInstance(property, toResourceInstance, false, index, resourceInstanceId);
-
- if (addPropertyToResourceInstance.isRight() && addPropertyToResourceInstance.right().value() != TitanOperationStatus.OK) {
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyToResourceInstance.right().value());
- return storageStatus;
- }
- if (addPropertyToResourceInstance.isLeft()) {
- ComponentInstanceProperty newProp = addPropertyToResourceInstance.left().value();
- Set<String> inputsKey = inputsPropMap.keySet();
- String inputToAssName = null;
- GetInputValueDataDefinition getInputInfo = null;
- for (String inputName : inputsKey) {
- List<ComponentInstanceProperty> propsList = inputsPropMap.get(inputName);
- Optional<ComponentInstanceProperty> op = propsList.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
- if (op.isPresent()) {
- ComponentInstanceProperty inpProp = op.get();
- getInputInfo = new GetInputValueDataDefinition();
- getInputInfo.setPropName(inpProp.getName());
- getInputInfo.setInputName(inputName);
- inputToAssName = inputName;
- break;
- }
-
- }
- if (inputToAssName != null) {
- for (InputDefinition input1 : newInputs) {
- if (input1.getName().equals(inputToAssName)) {
- this.inputOperation.associatePropertyToInput(riId, input1.getUniqueId(), newProp, getInputInfo);
- break;
- }
- }
- }
-
- }
- }
-
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus cloneResourceInstanceInputsValues(ComponentInstance toResourceInstance, ComponentInstance fromResourceInstance, Component comonentTo, Map<String, List<ComponentInstanceInput>> inputsValuesMap) {
-
- Either<List<ComponentInstanceInput>, TitanOperationStatus> allProperties = inputOperation.getAllInputsOfResourceInstanceOnlyInputDefId(fromResourceInstance.getUniqueId());
- if (allProperties.isRight()) {
- TitanOperationStatus status = allProperties.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.OK;
- }
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- return storageStatus;
- }
-
- List<ComponentInstanceInput> propertiesOnInstance = allProperties.left().value();
- if (propertiesOnInstance == null || propertiesOnInstance.isEmpty() == true) {
- return StorageOperationStatus.OK;
- }
- List<InputDefinition> newInputs = comonentTo.getInputs();
-
- for (ComponentInstanceInput property : propertiesOnInstance) {
-
- List<InputDefinition> inputToAss = new ArrayList<InputDefinition>();
- if (newInputs != null && !inputsValuesMap.isEmpty()) {
-
- Set<String> inputsName = inputsValuesMap.keySet();
- for (String name : inputsName) {
- List<ComponentInstanceInput> inputsValue = inputsValuesMap.get(name);
- if (inputsValue != null) {
- Optional<ComponentInstanceInput> op = inputsValue.stream().filter(p -> p.getValueUniqueUid().equals(property.getValueUniqueUid())).findAny();
- if (op.isPresent()) {
- Optional<InputDefinition> optional = newInputs.stream().filter(e -> e.getName().equals(name)).findAny();
- if (optional.isPresent()) {
- inputToAss.add(optional.get());
- }
- }
- }
- }
- }
-
- // Only if valueUniqueId is not empty, then its belongs to the
- // instance
- if (property.getValueUniqueUid() != null) {
- property.setValueUniqueUid(null);
- List<PropertyRule> rules = property.getRules();
- if (rules != null) {
- for (PropertyRule propertyRule : rules) {
- propertyRule.replaceFirstToken(toResourceInstance.getUniqueId());
- }
- }
-
- } else {
- continue;
- }
-
- String resourceInstanceId = toResourceInstance.getUniqueId();
-
- Either<Integer, StorageOperationStatus> counterRes = this.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.INPUT_COUNTER, true);
-
- if (counterRes.isRight()) {
- log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property);
- StorageOperationStatus status = counterRes.right().value();
- return status;
- }
- Integer index = counterRes.left().value();
-
- Either<InputValueData, TitanOperationStatus> addPropertyToResourceInstance = this.addInputToResourceInstance(property, toResourceInstance.getUniqueId(), index);
-
- if (addPropertyToResourceInstance.isRight()) {
- TitanOperationStatus status = addPropertyToResourceInstance.right().value();
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- return storageStatus;
- }
-
- for (InputDefinition input : inputToAss) {
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), input.getName());
- props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), toResourceInstance.getUniqueId());
-
- GraphNode inputData = new UniqueIdData(NodeTypeEnum.Input, input.getUniqueId());
- GraphNode propertyData = new UniqueIdData(NodeTypeEnum.InputValue, addPropertyToResourceInstance.left().value().getUniqueId());
-
- Either<GraphRelation, TitanOperationStatus> addPropRefResult = titanGenericDao.createRelation(inputData, propertyData, GraphEdgeLabels.GET_INPUT, props);
-
- if (addPropRefResult.isRight()) {
- TitanOperationStatus status = addPropRefResult.right().value();
- log.debug("Failed to associate input {} to input value {} in graph. Status is {}", input.getUniqueId(), propertyData.getUniqueId(), status);
-
- return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- }
- }
- }
-
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus cloneResourceInstanceInputsValues(TitanVertex toResourceInstanceVertex, ComponentInstance fromResourceInstance, String instanceId, Resource newResource, Map<String, List<ComponentInstanceInput>> inputsValuesMap) {
-
- Either<List<ComponentInstanceInput>, TitanOperationStatus> allProperties = inputOperation.getAllInputsOfResourceInstanceOnlyInputDefId(fromResourceInstance.getUniqueId());
- if (allProperties.isRight()) {
- TitanOperationStatus status = allProperties.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.OK;
- }
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- return storageStatus;
- }
-
- List<ComponentInstanceInput> propertiesOnInstance = allProperties.left().value();
- if (propertiesOnInstance == null || propertiesOnInstance.isEmpty() == true) {
- return StorageOperationStatus.OK;
- }
-
- for (ComponentInstanceInput property : propertiesOnInstance) {
-
- // Only if valueUniqueId is not empty, then its belongs to the
- // instance
- if (property.getValueUniqueUid() != null) {
- property.setValueUniqueUid(null);
- List<PropertyRule> rules = property.getRules();
- if (rules != null) {
- for (PropertyRule propertyRule : rules) {
- propertyRule.replaceFirstToken(instanceId);
- }
- }
-
- } else {
- continue;
- }
-
- String resourceInstanceId = instanceId;
-
- Either<Integer, StorageOperationStatus> counterRes = this.increaseAndGetResourceInstanceSpecificCounter(toResourceInstanceVertex, GraphPropertiesDictionary.INPUT_COUNTER);
-
- if (counterRes.isRight()) {
- log.debug("increaseAndGetResourcePropertyCounter failed resource instance {} property {}", resourceInstanceId, property);
- StorageOperationStatus status = counterRes.right().value();
- return status;
- }
- Integer index = counterRes.left().value();
-
- Either<InputValueData, TitanOperationStatus> addPropertyToResourceInstance = this.addInputToResourceInstance(property, resourceInstanceId, index);
-
- if (addPropertyToResourceInstance.isRight()) {
- TitanOperationStatus status = addPropertyToResourceInstance.right().value();
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- return storageStatus;
- }
- }
-
- return StorageOperationStatus.OK;
- }
-
- public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean inTransaction) {
-
- Either<ComponentInstanceProperty, StorageOperationStatus> result = null;
-
- try {
- // TODO: verify validUniqueId exists
- Either<PropertyValueData, TitanOperationStatus> eitherStatus = this.updatePropertyOfResourceInstance(resourceInstanceProperty, resourceInstanceId, true);
-
- if (eitherStatus.isRight()) {
- log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", resourceInstanceProperty, resourceInstanceId, eitherStatus.right().value().name());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
- return result;
- } else {
- PropertyValueData propertyValueData = eitherStatus.left().value();
-
- ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, resourceInstanceProperty);
-
- log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult);
-
- Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(resourceInstanceProperty.getPath(), propertyValueData.getUniqueId(), resourceInstanceProperty.getDefaultValue());
- if (findDefaultValue.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()));
- return result;
- }
- String defaultValue = findDefaultValue.left().value();
- propertyValueResult.setDefaultValue(defaultValue);
- log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
-
- result = Either.left(propertyValueResult);
- return result;
- }
- }
-
- finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
private static final class UpdateDataContainer<SomeData, SomeValueData> {
final Wrapper<SomeValueData> valueDataWrapper;
final Wrapper<SomeData> dataWrapper;
@@ -4514,27 +256,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
}
- @Override
- public Either<AttributeValueData, TitanOperationStatus> createOrUpdateAttributeOfResourceInstance(ComponentInstanceProperty attributeInstanceProperty, String resourceInstanceId) {
- Either<AttributeValueData, TitanOperationStatus> result;
- // Create
- if (attributeInstanceProperty.getValueUniqueUid() == null) {
- Either<Integer, StorageOperationStatus> counterRes = increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, true);
- if (counterRes.isRight()) {
- BeEcompErrorManager.getInstance().logInternalFlowError("createOrUpdateAttributeOfResourceInstance", "Failed to get AttributeValueData Counter", ErrorSeverity.ERROR);
- result = Either.right(TitanOperationStatus.GENERAL_ERROR);
-
- } else {
- result = addAttributeToResourceInstance(attributeInstanceProperty, resourceInstanceId, counterRes.left().value());
- }
- }
- // Update
- else {
- result = updateAttributeOfResourceInstance(attributeInstanceProperty, resourceInstanceId);
- }
- return result;
- }
-
/**
* update value of attribute on resource instance
*
@@ -4603,160 +324,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
- /**
- * update value of attribute on resource instance
- *
- * @param resourceInstanceProerty
- * @param resourceInstanceId
- * @return
- */
- public Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance(ComponentInstanceProperty resourceInstanceProerty, String resourceInstanceId, boolean isValidate) {
-
- Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>();
- UpdateDataContainer<PropertyData, PropertyValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.PROPERTY_IMPL, (() -> PropertyData.class), (() -> PropertyValueData.class), NodeTypeEnum.Property,
- NodeTypeEnum.PropertyValue);
-
- preUpdateElementOfResourceInstanceValidations(updateDataContainer, resourceInstanceProerty, resourceInstanceId, errorWrapper);
- if (!errorWrapper.isEmpty()) {
- return Either.right(errorWrapper.getInnerElement());
- }
-
- else {
- String value = resourceInstanceProerty.getValue();
- // Specific Validation Logic
- PropertyData propertyData = updateDataContainer.getDataWrapper().getInnerElement();
-
- String innerType = null;
-
- PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
- String propertyType = propDataDef.getType();
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
- log.debug("The type of the property {} is {}", propertyData.getUniqueId(), propertyType);
-
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
- SchemaDefinition def = propDataDef.getSchema();
- if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- innerType = propDef.getType();
- }
- // Specific Update Logic
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(status);
- }
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes.left().value());
-
- String newValue = value;
- if (isValid.isRight()) {
- Boolean res = isValid.right().value();
- if (res == false) {
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- } else {
- Object object = isValid.left().value();
- if (object != null) {
- newValue = object.toString();
- }
- }
- PropertyValueData propertyValueData = updateDataContainer.getValueDataWrapper().getInnerElement();
- log.debug("Going to update property value from {} to {}", propertyValueData.getValue(), newValue);
- propertyValueData.setValue(newValue);
-
- ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProerty.getRules(), innerType, allDataTypes.left().value(), isValidate);
- if (pair.getRight() != null && pair.getRight() == false) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProerty.getName(), propertyType);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- propertyOperation.updateRulesInPropertyValue(propertyValueData, resourceInstanceProerty, resourceInstanceId);
-
- Either<PropertyValueData, TitanOperationStatus> updateRes = titanGenericDao.updateNode(propertyValueData, PropertyValueData.class);
- if (updateRes.isRight()) {
- TitanOperationStatus status = updateRes.right().value();
- return Either.right(status);
- } else {
- return Either.left(updateRes.left().value());
- }
- }
-
- }
-
- /**
- * update value of attribute on resource instance
- *
- * @param resourceInstanceProerty
- * @param resourceInstanceId
- * @return
- */
- public Either<InputValueData, TitanOperationStatus> updateInputOfResourceInstance(ComponentInstanceInput resourceInstanceProerty, String resourceInstanceId) {
-
- Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>();
- UpdateDataContainer<PropertyData, InputValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.INPUT_IMPL, (() -> PropertyData.class), (() -> InputValueData.class), NodeTypeEnum.Input, NodeTypeEnum.InputValue);
-
- preUpdateElementOfResourceInstanceValidations(updateDataContainer, resourceInstanceProerty, resourceInstanceId, errorWrapper);
- if (!errorWrapper.isEmpty()) {
- return Either.right(errorWrapper.getInnerElement());
- }
-
- else {
- String value = resourceInstanceProerty.getValue();
- // Specific Validation Logic
- PropertyData propertyData = updateDataContainer.getDataWrapper().getInnerElement();
-
- String innerType = null;
-
- PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
- String propertyType = propDataDef.getType();
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
- log.debug("The type of the property {} is {}", propertyData.getUniqueId(), propertyType);
-
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
- SchemaDefinition def = propDataDef.getSchema();
- if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- innerType = propDef.getType();
- }
- // Specific Update Logic
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(status);
- }
- /*
- * Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value());
- *
- * String newValue = value; if (isValid.isRight()) { Boolean res = isValid.right().value(); if (res == false) { return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } } else { Object object = isValid.left().value(); if (object !=
- * null) { newValue = object.toString(); } } InputValueData propertyValueData = updateDataContainer.getValueDataWrapper().getInnerElement(); log.debug("Going to update property value from " + propertyValueData.getValue() + " to " +
- * newValue); propertyValueData.setValue(newValue);
- *
- * ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProerty.getRules(), innerType, allDataTypes.left().value()); if (pair.getRight() != null && pair.getRight() == false) {
- * BeEcompErrorManager.getInstance(). logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProerty.getName(), propertyType); return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); }
- * propertyOperation.updateRulesInPropertyValue(propertyValueData, resourceInstanceProerty, resourceInstanceId);
- *
- * Either<PropertyValueData, TitanOperationStatus> updateRes = titanGenericDao.updateNode(propertyValueData, PropertyValueData.class); if (updateRes.isRight()) { TitanOperationStatus status = updateRes.right().value(); return
- * Either.right(status); } else { return Either.left(updateRes.left().value()); }
- */
- }
- return null;
-
- }
-
private <SomeData extends GraphNode, SomeValueData extends GraphNode> void preUpdateElementOfResourceInstanceValidations(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty,
String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) {
@@ -4855,287 +422,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
/**
* add property to resource instance
*
- * @param resourceInstanceProperty
- * @param resourceInstanceId
- * @param index
- * @return
- */
- public Either<PropertyValueData, TitanOperationStatus> addPropertyToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isValidate, Integer index) {
-
- Either<ComponentInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class);
-
- if (findResInstanceRes.isRight()) {
- TitanOperationStatus status = findResInstanceRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
-
- String propertyId = resourceInstanceProperty.getUniqueId();
- Either<PropertyData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
-
- if (findPropertyDefRes.isRight()) {
- TitanOperationStatus status = findPropertyDefRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
-
- String valueUniqueUid = resourceInstanceProperty.getValueUniqueUid();
- if (valueUniqueUid == null) {
-
- PropertyData propertyData = findPropertyDefRes.left().value();
- ComponentInstanceData resourceInstanceData = findResInstanceRes.left().value();
-
- ImmutablePair<TitanOperationStatus, String> isPropertyValueExists = propertyOperation.findPropertyValue(resourceInstanceId, propertyId);
- if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) {
- log.debug("The property {} already added to the resource instance {}", propertyId, resourceInstanceId);
- resourceInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight());
- Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfResourceInstance(resourceInstanceProperty, resourceInstanceId, isValidate);
- if (updatePropertyOfResourceInstance.isRight()) {
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR);
- return Either.right(updatePropertyOfResourceInstance.right().value());
- }
- return Either.left(updatePropertyOfResourceInstance.left().value());
- }
-
- if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) {
- log.debug("After finding property value of {} on componenet instance {}", propertyId, resourceInstanceId);
- return Either.right(isPropertyValueExists.getLeft());
- }
-
- String innerType = null;
-
- PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
- String propertyType = propDataDef.getType();
- String value = resourceInstanceProperty.getValue();
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
-
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
- SchemaDefinition def = propDataDef.getSchema();
- if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- innerType = propDef.getType();
- }
-
- log.debug("Before validateAndUpdatePropertyValue");
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(status);
- }
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes.left().value());
- log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
-
- String newValue = value;
- if (isValid.isRight()) {
- Boolean res = isValid.right().value();
- if (res == false) {
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- } else {
- Object object = isValid.left().value();
- if (object != null) {
- newValue = object.toString();
- }
- }
-
- String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(resourceInstanceData.getUniqueId(), index);
- PropertyValueData propertyValueData = new PropertyValueData();
- propertyValueData.setUniqueId(uniqueId);
- propertyValueData.setValue(newValue);
-
- log.debug("Before validateAndUpdateRules");
- ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProperty.getRules(), innerType, allDataTypes.left().value(), isValidate);
- log.debug("After validateAndUpdateRules. pair = {}", pair);
- if (pair.getRight() != null && pair.getRight() == false) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProperty.getName(), propertyType);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- propertyOperation.addRulesToNewPropertyValue(propertyValueData, resourceInstanceProperty, resourceInstanceId);
-
- log.debug("Before adding property value to graph {}", propertyValueData);
- Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class);
- log.debug("After adding property value to graph {}", propertyValueData);
-
- if (createNodeResult.isRight()) {
- TitanOperationStatus operationStatus = createNodeResult.right().value();
- return Either.right(operationStatus);
- }
- propertyValueData = createNodeResult.left().value();
-
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null);
-
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus);
- return Either.right(operationStatus);
- }
-
- createRelResult = titanGenericDao.createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null);
-
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, operationStatus);
- return Either.right(operationStatus);
- }
-
- return Either.left(propertyValueData);
- } else {
- log.error("property value already exists.");
- return Either.right(TitanOperationStatus.ALREADY_EXIST);
- }
-
- }
-
- public Either<ComponentInstanceProperty, TitanOperationStatus> addPropertyToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, TitanVertex resourceInstanceVertex, boolean isValidate, Integer index, String resourceInstanceId) {
-
- String propertyId = resourceInstanceProperty.getUniqueId();
- Either<PropertyData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
-
- if (findPropertyDefRes.isRight()) {
- TitanOperationStatus status = findPropertyDefRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
-
- String valueUniqueUid = resourceInstanceProperty.getValueUniqueUid();
- if (valueUniqueUid == null) {
-
- PropertyData propertyData = findPropertyDefRes.left().value();
-
- ImmutablePair<TitanOperationStatus, String> isPropertyValueExists = propertyOperation.findPropertyValue(resourceInstanceId, propertyId);
- if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) {
- log.trace("The property {} already added to the resource instance {}", propertyId, resourceInstanceId);
- resourceInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight());
- Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfResourceInstance(resourceInstanceProperty, resourceInstanceId, isValidate);
- if (updatePropertyOfResourceInstance.isRight()) {
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR);
- return Either.right(updatePropertyOfResourceInstance.right().value());
- }
- return Either.right(TitanOperationStatus.OK);
- }
-
- if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) {
- log.trace("After finding property value of {} on componenet instance {}", propertyId, resourceInstanceId);
- return Either.right(isPropertyValueExists.getLeft());
- }
-
- String innerType = null;
-
- PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
- String propertyType = propDataDef.getType();
- String value = resourceInstanceProperty.getValue();
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
-
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
- SchemaDefinition def = propDataDef.getSchema();
- if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- innerType = propDef.getType();
- }
-
- log.trace("Before validateAndUpdatePropertyValue");
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(status);
- }
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, allDataTypes.left().value());
- log.trace("After validateAndUpdatePropertyValue. isValid = {}", isValid);
-
- String newValue = value;
- if (isValid.isRight()) {
- Boolean res = isValid.right().value();
- if (res == false) {
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- } else {
- Object object = isValid.left().value();
- if (object != null) {
- newValue = object.toString();
- }
- }
-
- String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(resourceInstanceId, index);
- PropertyValueData propertyValueData = new PropertyValueData();
- propertyValueData.setUniqueId(uniqueId);
- propertyValueData.setValue(newValue);
-
- log.trace("Before validateAndUpdateRules");
- ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProperty.getRules(), innerType, allDataTypes.left().value(), isValidate);
- log.debug("After validateAndUpdateRules. pair = {} ", pair);
- if (pair.getRight() != null && pair.getRight() == false) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProperty.getName(), propertyType);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- propertyOperation.addRulesToNewPropertyValue(propertyValueData, resourceInstanceProperty, resourceInstanceId);
-
- log.trace("Before adding property value to graph {}", propertyValueData);
- Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class);
- log.trace("After adding property value to graph {}", propertyValueData);
-
- if (createNodeResult.isRight()) {
- TitanOperationStatus operationStatus = createNodeResult.right().value();
- return Either.right(operationStatus);
- }
- propertyValueData = createNodeResult.left().value();
-
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null);
-
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus);
- return Either.right(operationStatus);
- }
-
- TitanOperationStatus edgeResult = titanGenericDao.createEdge(resourceInstanceVertex, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null);
-
- if (edgeResult != TitanOperationStatus.OK) {
- log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, edgeResult);
- return Either.right(edgeResult);
- }
-
- ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, resourceInstanceProperty);
- log.debug("The returned ResourceInstanceProperty is {} ", propertyValueResult);
-
- return Either.left(propertyValueResult);
- } else {
- log.debug("property value already exists.");
- return Either.right(TitanOperationStatus.ALREADY_EXIST);
- }
-
- }
-
- /**
- * add property to resource instance
- *
- * @param resourceInstanceProperty
* @param resourceInstanceId
* @param index
* @return
*/
- public Either<InputValueData, TitanOperationStatus> addInputToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index) {
+ private Either<InputValueData, TitanOperationStatus> addInputToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index) {
Either<ComponentInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class);
@@ -5256,10 +547,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
- // inputOperation.associatePropertyToInput(resourceInstanceId,
- // resourceInstanceInput.getInputId(), propertyValueData,
- // resourceInstanceInput.getName());
-
return Either.left(createNodeResult.left().value());
} else {
log.error("property value already exists.");
@@ -5283,7 +570,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
} else {
AttributeValueData attributeValueData = eitherStatus.left().value();
- ComponentInstanceProperty attributeValueResult = attributeOperation.buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute);
+ ComponentInstanceProperty attributeValueResult = buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute);
log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult);
result = Either.left(attributeValueResult);
@@ -5296,6 +583,12 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
}
+ private ComponentInstanceProperty buildResourceInstanceAttribute(AttributeValueData attributeValueData, ComponentInstanceProperty resourceInstanceAttribute) {
+ Boolean hidden = attributeValueData.isHidden();
+ String uid = attributeValueData.getUniqueId();
+ return new ComponentInstanceProperty(hidden, resourceInstanceAttribute, uid);
+ }
+
@Override
public Either<ComponentInstanceProperty, StorageOperationStatus> updateAttributeValueInResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, boolean inTransaction) {
@@ -5311,7 +604,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
} else {
AttributeValueData attributeValueData = eitherAttributeValue.left().value();
- ComponentInstanceProperty attributeValueResult = attributeOperation.buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute);
+ ComponentInstanceProperty attributeValueResult = buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute);
log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult);
result = Either.left(attributeValueResult);
@@ -5326,64 +619,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
@Override
- public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, boolean inTransaction) {
- return addPropertyValueToResourceInstance(resourceInstanceProperty, resourceInstanceId, true, index, inTransaction);
- }
-
- @Override
- public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isValidate, Integer index, boolean inTransaction) {
-
- /// #RULES SUPPORT
- /// Ignore rules received from client till support
- resourceInstanceProperty.setRules(null);
- ///
- ///
-
- Either<ComponentInstanceProperty, StorageOperationStatus> result = null;
-
- try {
-
- Either<PropertyValueData, TitanOperationStatus> eitherStatus = addPropertyToResourceInstance(resourceInstanceProperty, resourceInstanceId, isValidate, index);
-
- if (eitherStatus.isRight()) {
- log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", resourceInstanceProperty, resourceInstanceId, eitherStatus.right().value().name());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
- return result;
- } else {
- PropertyValueData propertyValueData = eitherStatus.left().value();
-
- ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, resourceInstanceProperty);
- log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult);
-
- Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(resourceInstanceProperty.getPath(), resourceInstanceProperty.getUniqueId(), resourceInstanceProperty.getDefaultValue());
- if (findDefaultValue.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()));
- return result;
- }
- String defaultValue = findDefaultValue.left().value();
- propertyValueResult.setDefaultValue(defaultValue);
- log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
-
- result = Either.left(propertyValueResult);
- return result;
- }
- }
-
- finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
public Either<ComponentInstanceInput, StorageOperationStatus> addInputValueToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index, boolean inTransaction) {
/// #RULES SUPPORT
@@ -5436,636 +671,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
}
- public Either<List<ComponentInstanceProperty>, TitanOperationStatus> getComponentInstancesProperties(List<ComponentInstance> resourceInstances, Map<String, List<PropertyDefinition>> alreadyProcessedResources,
- Map<String, List<ComponentInstanceProperty>> resourceInstancesProperties, Map<String, ImmutablePair<ComponentInstance, Integer>> processedInstances, List<String> path) {
-
- List<ComponentInstanceProperty> result = new ArrayList<>();
-
- for (ComponentInstance componentInstance : resourceInstances) {
-
- path.add(componentInstance.getUniqueId());
-
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> componentInstancesProperties = getComponentInstanceProperties(componentInstance, alreadyProcessedResources, resourceInstancesProperties, processedInstances, path);
- if (componentInstancesProperties.isRight()) {
- TitanOperationStatus status = componentInstancesProperties.right().value();
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
- }
-
- List<ComponentInstanceProperty> compInstancePropertyList = componentInstancesProperties.left().value();
- if (compInstancePropertyList != null) {
- result.addAll(compInstancePropertyList);
- }
-
- String uniqueId = componentInstance.getUniqueId();
- if (false == processedInstances.containsKey(uniqueId)) {
- processedInstances.put(uniqueId, new ImmutablePair<ComponentInstance, Integer>(componentInstance, path.size()));
- }
- path.remove(path.size() - 1);
-
- }
-
- return Either.left(result);
- }
-
- //US831698
- public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstancesPropertiesAndValuesFromGraph(ComponentInstance resourceInstance) {
-
- Map<String, List<PropertyDefinition>> alreadyProcessedResources = new HashMap<>();
- Map<String, List<ComponentInstanceProperty>> alreadyProcessedInstances = new HashMap<>();
- Map<String, ImmutablePair<ComponentInstance, Integer>> processedInstances = new HashMap<>();
- Map<String, List<ComponentInstanceProperty>> resourceInstancesProperties = new HashMap<>();
-
- List<String> path = new ArrayList<>();
- path.add(resourceInstance.getUniqueId());
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> componentInstanceProperties = getComponentInstanceProperties(resourceInstance, alreadyProcessedResources, alreadyProcessedInstances, processedInstances, path);
-
- if (componentInstanceProperties.isRight()) {
- StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(componentInstanceProperties.right().value());
- return Either.right(convertTitanStatusToStorageStatus);
- }
-
- List<ComponentInstanceProperty> listOfProps = componentInstanceProperties.left().value();
- resourceInstancesProperties.put(resourceInstance.getUniqueId(), listOfProps);
-
- processedInstances.put(resourceInstance.getUniqueId(), new ImmutablePair<ComponentInstance, Integer>(resourceInstance, path.size()));
- path.remove(path.size() - 1);
-
- Either<Map<String, Map<String, ComponentInstanceProperty>>, TitanOperationStatus> findAllPropertiesValuesOnInstances = findAllPropertyValueOnInstances(processedInstances);
- // 1. check status
- if (findAllPropertiesValuesOnInstances.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findAllPropertiesValuesOnInstances.right().value()));
- }
-
- propertyOperation.updatePropertiesByPropertyValues(resourceInstancesProperties, findAllPropertiesValuesOnInstances.left().value());
-
- return Either.left(resourceInstancesProperties.get(resourceInstance.getUniqueId()));
- }
-
- public Either<List<ComponentInstanceProperty>, TitanOperationStatus> getComponentInstanceProperties(ComponentInstance resourceInstance, Map<String, List<PropertyDefinition>> alreadyProcessedResources,
- Map<String, List<ComponentInstanceProperty>> alreadyProcessedInstances, Map<String, ImmutablePair<ComponentInstance, Integer>> processedInstances, List<String> path) {
-
- // 1. Go over each instance
- // 1.1 get all properties of from the parents of the instance
- // 1.2 get all updated properties
- // 1.3 find all instances included in the parent of this instance and
- // run this method on them.
- if (log.isDebugEnabled())
- log.debug("Going to update properties of resource instance {}", resourceInstance.getUniqueId());
- String resourceUid = resourceInstance.getComponentUid();
-
- List<PropertyDefinition> properties = alreadyProcessedResources.get(resourceUid);
- if (properties == null) {
- properties = new ArrayList<>();
- TitanOperationStatus findAllRes = propertyOperation.findAllResourcePropertiesRecursively(resourceUid, properties);
- if (findAllRes != TitanOperationStatus.OK) {
- return Either.right(findAllRes);
- }
- alreadyProcessedResources.put(resourceUid, properties);
- }
-
- if (log.isDebugEnabled())
- log.debug("After getting properties of resource {} . Number of properties is {}", resourceUid, (properties == null ? 0 : properties.size()));
- List<ComponentInstanceProperty> resourceInstancePropertyList = new ArrayList<>();
- if (false == properties.isEmpty()) {
-
- // TODO: WE MAY HAVE INDIRECT PROPERTY VALUE ALSO IN CASE NO
- // PROPERTY ON THIS COMPONENT
-
- // String resourceInstanceUid = resourceInstance.getUniqueId();
-
- for (PropertyDefinition propertyDefinition : properties) {
-
- String defaultValue = propertyDefinition.getDefaultValue();
- String value = defaultValue;
- String valueUid = null;
-
- // String propertyId = propertyDefinition.getUniqueId();
-
- ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty(propertyDefinition, value, valueUid);
-
- resourceInstanceProperty.setPath(cloneList(path));
-
- // TODO: currently ignore constraints since they are not inuse
- // and cause to error in convertion to object.
- resourceInstanceProperty.setConstraints(null);
-
- resourceInstancePropertyList.add(resourceInstanceProperty);
-
- }
- }
-
- OriginTypeEnum originType = resourceInstance.getOriginType();
-
- Either<List<ComponentInstance>, TitanOperationStatus> findInstancesUnderParentOfInstance = findInstancesUnderParentOfInstance(originType, resourceUid);
-
- if (findInstancesUnderParentOfInstance.isRight()) {
- TitanOperationStatus status = findInstancesUnderParentOfInstance.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- return Either.right(status);
- }
- } else {
- List<ComponentInstance> listOfInstances = findInstancesUnderParentOfInstance.left().value();
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> componentInstancesProperties = getComponentInstancesProperties(listOfInstances, alreadyProcessedResources, alreadyProcessedInstances, processedInstances, path);
- if (componentInstancesProperties.isRight()) {
- TitanOperationStatus status = componentInstancesProperties.right().value();
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
- }
- List<ComponentInstanceProperty> currentList = componentInstancesProperties.left().value();
- if (currentList != null) {
- resourceInstancePropertyList.addAll(currentList);
- }
- }
-
- return Either.left(resourceInstancePropertyList);
- }
-
- public Either<List<ComponentInstance>, TitanOperationStatus> findInstancesUnderParentOfInstance(OriginTypeEnum originType, String resourceUid) {
-
- NodeTypeEnum containerNodeType = null;
- NodeTypeEnum compInstNodeType = null;
-
- switch (originType) {
-
- case VF:
- containerNodeType = NodeTypeEnum.Resource;
- compInstNodeType = NodeTypeEnum.Resource;
- break;
- case SERVICE:
- containerNodeType = NodeTypeEnum.Service;
- compInstNodeType = NodeTypeEnum.Resource;
- break;
- case PRODUCT:
- containerNodeType = NodeTypeEnum.Product;
- compInstNodeType = NodeTypeEnum.Service;
- break;
- case VFC:
- case VFCMT:
- case VL:
- case CP:
- break;
- default:
- break;
- }
-
- if (containerNodeType == null || compInstNodeType == null) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> componentInstancesOfComponent = this.getComponentInstancesOfComponent(resourceUid, containerNodeType, compInstNodeType);
-
- if (componentInstancesOfComponent.isRight()) {
- TitanOperationStatus status = componentInstancesOfComponent.right().value();
- log.debug("After getting instances of {} from type {}. Status is {}", resourceUid, originType, status);
- return Either.right(status);
- } else {
- List<ComponentInstance> listOfInstances = componentInstancesOfComponent.left().value().getLeft();
- if (log.isDebugEnabled()) {
- String msg = "After getting instances of {} from type {} {}.";
- log.debug(msg, resourceUid, originType, (listOfInstances != null ? listOfInstances.size() : 0));
- if (log.isTraceEnabled())
- log.trace(msg, resourceUid, originType, listOfInstances);
- }
- return Either.left(listOfInstances);
- }
-
- }
-
- private List<String> cloneList(List<String> list) {
-
- if (list == null) {
- return null;
- }
-
- List<String> clonedList = new ArrayList<String>();
- clonedList.addAll(list);
-
- return clonedList;
- }
-
- public Either<Map<String, Map<String, ComponentInstanceProperty>>, TitanOperationStatus> findAllPropertyValueOnInstances(Map<String, ImmutablePair<ComponentInstance, Integer>> processedInstances) {
-
- if (processedInstances == null) {
- return Either.right(TitanOperationStatus.OK);
- }
-
- Set<Entry<String, ImmutablePair<ComponentInstance, Integer>>> entrySet = processedInstances.entrySet();
-
- Map<String, Map<String, ComponentInstanceProperty>> propertyToInstanceValue = new HashMap<>();
-
- for (Entry<String, ImmutablePair<ComponentInstance, Integer>> entry : entrySet) {
-
- String compInstUniqueId = entry.getKey();
-
- ImmutablePair<ComponentInstance, Integer> pair = entry.getValue();
-
- ComponentInstance componentInstance = pair.getLeft();
-
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> propeprtyValueOnCIResult = findPropertyValueOnComponentInstance(componentInstance);
-
- if (propeprtyValueOnCIResult.isRight()) {
- TitanOperationStatus status = propeprtyValueOnCIResult.right().value();
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
- continue;
- }
-
- List<ComponentInstanceProperty> propertyValuesOnCI = propeprtyValueOnCIResult.left().value();
- if (propertyValuesOnCI != null) {
- for (ComponentInstanceProperty instanceProperty : propertyValuesOnCI) {
- boolean result = addPropertyValue(compInstUniqueId, instanceProperty, propertyToInstanceValue);
- if (!result) {
- return Either.right(TitanOperationStatus.ALREADY_EXIST);
- }
- }
- }
-
- }
-
- return Either.left(propertyToInstanceValue);
- }
-
- private boolean addPropertyValue(String compInstUniqueId, ComponentInstanceProperty instanceProperty, Map<String, Map<String, ComponentInstanceProperty>> propertyToInstanceValue) {
-
- String propertyUid = instanceProperty.getUniqueId();
-
- Map<String, ComponentInstanceProperty> map = propertyToInstanceValue.get(propertyUid);
- if (map == null) {
- map = new HashMap<>();
- propertyToInstanceValue.put(propertyUid, map);
- }
-
- ComponentInstanceProperty putIfAbsent = map.putIfAbsent(compInstUniqueId, instanceProperty);
- if (putIfAbsent != null) {
- BeEcompErrorManager.getInstance().logInternalUnexpectedError("find property value", "Found 2 values on the same instance", ErrorSeverity.ERROR);
- return false;
- }
-
- return true;
-
- }
-
- private boolean addInputValue(String compInstUniqueId, ComponentInstanceInput instanceProperty, Map<String, Map<String, ComponentInstanceInput>> propertyToInstanceValue) {
-
- String propertyUid = instanceProperty.getUniqueId();
-
- Map<String, ComponentInstanceInput> map = propertyToInstanceValue.get(propertyUid);
- if (map == null) {
- map = new HashMap<>();
- propertyToInstanceValue.put(propertyUid, map);
- }
-
- ComponentInstanceInput putIfAbsent = map.putIfAbsent(compInstUniqueId, instanceProperty);
- if (putIfAbsent != null) {
- BeEcompErrorManager.getInstance().logInternalUnexpectedError("find property value", "Found 2 values on the same instance", ErrorSeverity.ERROR);
- return false;
- }
-
- return true;
-
- }
-
- private Either<List<ComponentInstanceProperty>, TitanOperationStatus> findPropertyValueOnComponentInstance(ComponentInstance componentInstance) {
- String resourceInstanceUid = componentInstance.getUniqueId();
- OriginTypeEnum originType = componentInstance.getOriginType();
-
- NodeTypeEnum instanceNodeType = findInstanceNodeTypeEnumFromOriginType(originType);
-
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> propertyValuesResult = propertyOperation.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceUid, instanceNodeType);
-
- log.debug("After fetching property under resource instance {}", resourceInstanceUid);
- if (propertyValuesResult.isRight()) {
- TitanOperationStatus status = propertyValuesResult.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- return Either.right(status);
- }
- return Either.right(TitanOperationStatus.OK);
- }
-
- return Either.left(propertyValuesResult.left().value());
-
- }
-
- private NodeTypeEnum findInstanceNodeTypeEnumFromOriginType(OriginTypeEnum originType) {
- NodeTypeEnum nodeType = NodeTypeEnum.ResourceInstance;
- switch (originType) {
- case SERVICE:
- nodeType = NodeTypeEnum.ResourceInstance;
- break;
- default:
- break;
- }
-
- return nodeType;
- }
-
- /**
- * add capability property values to resource instance
- *
- * @param resourceInstanceId
- * @param capability
- * @param isNewlyCreatedResourceInstance
- * @return
- */
- public Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> addCapabilityPropertyValuesToResourceInstance(String resourceInstanceId, CapabilityDefinition capability, boolean isNewlyCreatedResourceInstance) {
- log.debug("Before adding capability property values to resource instance {}.", resourceInstanceId);
- TitanOperationStatus error = null;
-
- Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> addCapInstWithPropertiesRes = capabilityInstanceOperation.createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(resourceInstanceId,
- capability.getUniqueId(), capability.getName(), capability.getProperties(), !isNewlyCreatedResourceInstance);
- if (addCapInstWithPropertiesRes.isRight()) {
- error = addCapInstWithPropertiesRes.right().value();
- log.debug("Failed to assotiate capability instance to resource instance {}. status is {}", resourceInstanceId, error);
- }
- log.debug("After adding capability property values to resource instance {}. Status is {}", resourceInstanceId, error);
- if (error == null) {
- return Either.left(addCapInstWithPropertiesRes.left().value());
- }
- return Either.right(error);
- }
-
- public TitanOperationStatus addCapabilityPropertyValuesToResourceInstance(TitanVertex resourceInstanceVertex, String resourceInstanceId, CapabilityDefinition capability, boolean isNewlyCreatedResourceInstance) {
- log.trace("Before adding capability property values to resource instance {}.", resourceInstanceId);
- TitanOperationStatus error = TitanOperationStatus.OK;
-
- TitanOperationStatus addCapInstWithPropertiesRes = capabilityInstanceOperation.createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(resourceInstanceVertex, resourceInstanceId, capability.getUniqueId(),
- capability.getName(), capability.getProperties(), !isNewlyCreatedResourceInstance);
- if (addCapInstWithPropertiesRes != TitanOperationStatus.OK) {
- error = addCapInstWithPropertiesRes;
- log.debug("Failed to assotiate capability instance to resource instance {} . status is {}", resourceInstanceId, error);
- }
- log.debug("After adding capability property values to resource instance {}. Status is {}", resourceInstanceId, error);
-
- return error;
- }
-
- /**
- * update capability property values of capability
- *
- * @param resourceInstanceId
- * @param capabilityId
- * @param propertyValues
- * @return
- */
- public Either<List<PropertyValueData>, TitanOperationStatus> updateCapabilityPropertyValuesOfResourceInstance(String resourceInstanceId, String capabilityId, List<ComponentInstanceProperty> propertyValues) {
- log.debug("Before updating property values of capability {} of resource instance {}.", capabilityId, resourceInstanceId);
- TitanOperationStatus error = null;
- Either<List<PropertyValueData>, TitanOperationStatus> updateCapabilityPropertyValuesRes = capabilityInstanceOperation.updateCapabilityPropertyValues(resourceInstanceId, capabilityId, propertyValues);
- if (updateCapabilityPropertyValuesRes.isRight()) {
- error = updateCapabilityPropertyValuesRes.right().value();
- log.debug("Failed to update property values of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error);
- }
- log.debug("After updating property values of capability {} of resource instance {}. Status is {}", capabilityId, resourceInstanceId, error);
- if (error == null) {
- return Either.left(updateCapabilityPropertyValuesRes.left().value());
- }
- return Either.right(error);
- }
-
- /**
- * delete property values of capability from resource instance
- *
- * @param capabilityId
- * @param resourceInstanceId
- * @return
- */
- public Either<CapabilityInstData, TitanOperationStatus> deletePropertyValuesOfCapabilityFromResourceInstance(String capabilityId, String resourceInstanceId) {
- log.debug("Before deleting property values of capability {} from resource instance {}.", capabilityId, resourceInstanceId);
- TitanOperationStatus error = null;
- Either<CapabilityInstData, TitanOperationStatus> deleteCapInstWithPropertiesRes = null;
- Either<CapabilityInstData, TitanOperationStatus> getCapInstByCapabilityRes = capabilityInstanceOperation.getCapabilityInstanceOfCapabilityOfResourceInstance(resourceInstanceId, capabilityId);
- if (getCapInstByCapabilityRes.isRight()) {
- error = getCapInstByCapabilityRes.right().value();
- log.debug("Failed to retrieve capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error);
- }
- if (error == null) {
- String capabilityInstanceId = getCapInstByCapabilityRes.left().value().getUniqueId();
- deleteCapInstWithPropertiesRes = capabilityInstanceOperation.deleteCapabilityInstanceFromResourceInstance(resourceInstanceId, capabilityInstanceId);
- if (deleteCapInstWithPropertiesRes.isRight()) {
- error = deleteCapInstWithPropertiesRes.right().value();
- log.debug("Failed to delete capability instance {} to resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error);
- }
- }
- log.debug("After deleting property values of capability {} from resource instance {}. Status is {}", capabilityId, resourceInstanceId, error);
- if (error == null) {
- return Either.left(deleteCapInstWithPropertiesRes.left().value());
- }
- return Either.right(error);
- }
-
- /**
- * clone capability instances of resource instance
- *
- * @param createdComponentInstance
- * @param resourceInstance
- * @return
- */
- private Either<Map<ImmutablePair<CapabilityInstData, GraphEdge>, List<PropertyValueData>>, TitanOperationStatus> cloneCapabilityInstancesOfResourceInstance(ComponentInstanceData createdComponentInstance, ComponentInstance resourceInstance) {
- TitanOperationStatus error = null;
- String resourceInstanceId = resourceInstance.getUniqueId();
- log.debug("Before cloning of capability instances of resource instance {}.", resourceInstanceId);
-
- Map<ImmutablePair<CapabilityInstData, GraphEdge>, List<PropertyValueData>> result = new HashMap<>();
- Either<ImmutablePair<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> cloneAssociateCIWithPropertyValuesRes;
- Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesRes = capabilityInstanceOperation.getAllCapabilityInstancesOfResourceInstance(resourceInstanceId);
- if (getAllCapabilityInstancesRes.isRight() && !getAllCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- error = getAllCapabilityInstancesRes.right().value();
- log.debug("Failed to get capability instances of component instance {}. status is {}", resourceInstanceId, error);
- }
- if (getAllCapabilityInstancesRes.isLeft()) {
- List<ImmutablePair<CapabilityInstData, GraphEdge>> capabilityInstances = getAllCapabilityInstancesRes.left().value();
- Map<String, List<CapabilityDefinition>> allCapabilitiesMap = resourceInstance.getCapabilities();
- List<CapabilityDefinition> allCapabilitiesList = new ArrayList<>();
- for (List<CapabilityDefinition> curList : allCapabilitiesMap.values()) {
- allCapabilitiesList.addAll(curList);
- }
- Map<String, CapabilityDefinition> capabilities = allCapabilitiesList.stream().collect(Collectors.toMap(CapabilityDefinition::getUniqueId, Function.identity()));
- String propertyName = GraphPropertiesDictionary.CAPABILITY_ID.getProperty();
- for (ImmutablePair<CapabilityInstData, GraphEdge> capabilityInstPair : capabilityInstances) {
- String capabilityId = (String) capabilityInstPair.getRight().getProperties().get(propertyName);
- CapabilityDefinition relatedCapability = capabilities.get(capabilityId);
- cloneAssociateCIWithPropertyValuesRes = capabilityInstanceOperation.cloneAssociateCapabilityInstanceWithPropertyValues(createdComponentInstance, relatedCapability, capabilityInstPair);
- if (cloneAssociateCIWithPropertyValuesRes.isRight()) {
- error = cloneAssociateCIWithPropertyValuesRes.right().value();
- log.debug("Failed to clone capability instances {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), resourceInstanceId, error);
- break;
- } else {
- result.put(new ImmutablePair<CapabilityInstData, GraphEdge>(cloneAssociateCIWithPropertyValuesRes.left().value().getLeft(), capabilityInstPair.getRight()), cloneAssociateCIWithPropertyValuesRes.left().value().getRight());
- }
- }
- }
- log.debug("After cloning of capability instance of resource instance {}. Status is {}", resourceInstanceId, error);
- if (error == null) {
- return Either.left(result);
- }
- return Either.right(error);
- }
-
- private Either<List<ImmutablePair<TitanVertex, GraphEdge>>, TitanOperationStatus> cloneCapabilityInstancesOfResourceInstance(TitanVertex componentInstanceVertex, ComponentInstance resourceInstance) {
- TitanOperationStatus error = null;
- String resourceInstanceId = resourceInstance.getUniqueId();
- log.debug("Before cloning of capability instances of resource instance {}.", resourceInstanceId);
-
- Either<TitanVertex, TitanOperationStatus> cloneAssociateCIWithPropertyValuesRes = null;
- Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesRes = capabilityInstanceOperation.getAllCapabilityInstancesOfResourceInstance(resourceInstanceId);
- if (getAllCapabilityInstancesRes.isRight() && getAllCapabilityInstancesRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- error = getAllCapabilityInstancesRes.right().value();
- log.debug("Failed to get capability instances of component instance {}. status is {}", resourceInstanceId, error);
- }
- List<ImmutablePair<TitanVertex, GraphEdge>> list = new ArrayList<>();
- if (getAllCapabilityInstancesRes.isLeft()) {
- List<ImmutablePair<CapabilityInstData, GraphEdge>> capabilityInstances = getAllCapabilityInstancesRes.left().value();
- Map<String, List<CapabilityDefinition>> allCapabilitiesMap = resourceInstance.getCapabilities();
- List<CapabilityDefinition> allCapabilitiesList = new ArrayList<>();
- for (List<CapabilityDefinition> curList : allCapabilitiesMap.values()) {
- allCapabilitiesList.addAll(curList);
- }
- Map<String, CapabilityDefinition> capabilities = allCapabilitiesList.stream().collect(Collectors.toMap(CapabilityDefinition::getUniqueId, Function.identity()));
- String propertyName = GraphPropertiesDictionary.CAPABILITY_ID.getProperty();
- for (ImmutablePair<CapabilityInstData, GraphEdge> capabilityInstPair : capabilityInstances) {
- String capabilityId = (String) capabilityInstPair.getRight().getProperties().get(propertyName);
- CapabilityDefinition relatedCapability = capabilities.get(capabilityId);
- cloneAssociateCIWithPropertyValuesRes = capabilityInstanceOperation.cloneAssociateCapabilityInstanceWithPropertyValues(componentInstanceVertex, relatedCapability, capabilityInstPair);
- if (cloneAssociateCIWithPropertyValuesRes.isRight()) {
- error = cloneAssociateCIWithPropertyValuesRes.right().value();
- log.debug("Failed to clone capability instances {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), resourceInstanceId, error);
- break;
- } else {
- list.add(new ImmutablePair<TitanVertex, GraphEdge>(cloneAssociateCIWithPropertyValuesRes.left().value(), capabilityInstPair.right));
- }
- }
- }
- log.debug("After cloning of capability instance of resource instance {}. Status is {}", resourceInstanceId, error);
- if (error == null) {
- return Either.left(list);
- }
- return Either.right(error);
- }
-
- public Either<List<ComponentInstance>, StorageOperationStatus> getAllComponentInstancesMetadataOnly(String componentId, NodeTypeEnum containerNodeType) {
-
- List<ComponentInstance> componentInstancesResult = new ArrayList<ComponentInstance>();
- Either<List<ComponentInstance>, StorageOperationStatus> result = Either.left(componentInstancesResult);
-
- Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> resourceInstancesRes = getAllComponentInstanceFromGraph(componentId, containerNodeType, false);
-
- if (resourceInstancesRes.isRight()) {
-
- if (log.isDebugEnabled()) {
- log.debug("Resource instance was found under service {} . status is {} ", componentId, resourceInstancesRes.right().value());
- }
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceInstancesRes.right().value()));
- }
-
- List<ImmutablePair<ComponentInstanceData, GraphEdge>> resourceInstances = resourceInstancesRes.left().value();
- if (resourceInstances != null && false == resourceInstances.isEmpty()) {
-
- for (ImmutablePair<ComponentInstanceData, GraphEdge> immutablePair : resourceInstances) {
- ComponentInstanceData resourceInstanceData = immutablePair.getKey();
- if (log.isDebugEnabled()) {
- log.debug("Going to fetch the relationships of resource instance {}", resourceInstanceData);
- }
- componentInstancesResult.add(new ComponentInstance(resourceInstanceData.getComponentInstDataDefinition()));
-
- }
- }
-
- return result;
- }
-
- public Either<List<CapabilityDefinition>, TitanOperationStatus> updateCapDefPropertyValues(ComponentInstance componentInstance, List<CapabilityDefinition> capabilityDefList) {
- String componentInstanceId = componentInstance.getUniqueId();
- log.debug("Before updating property values of capabilities of component istance {}.", componentInstanceId);
- TitanOperationStatus error = null;
- NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentInstance.getOriginType().getInstanceType().trim());
-
- log.debug("Before getting all capability instances of component istance {}.", componentInstanceId);
- Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), componentInstanceId, GraphEdgeLabels.CAPABILITY_INST,
- NodeTypeEnum.CapabilityInst, CapabilityInstData.class);
- if (getCapabilityInstancesRes.isRight() && !getCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- error = getCapabilityInstancesRes.right().value();
- log.debug("Failed to retrieve capability Instances of resource instance {}. Status is {}", componentInstance.getName(), error);
- }
- log.debug("After getting all capability instances of component istance {}. Status is {}", componentInstanceId, error);
- Map<String, Map<String, PropertyValueData>> overridedCapabilitiesHM = new HashMap<>();
- if (getCapabilityInstancesRes.isLeft()) {
- List<ImmutablePair<CapabilityInstData, GraphEdge>> capabilityInstDataPair = getCapabilityInstancesRes.left().value();
-
- for (ImmutablePair<CapabilityInstData, GraphEdge> curCapabilityPair : capabilityInstDataPair) {
- CapabilityInstData curCapabilityInst = curCapabilityPair.getLeft();
- String curCapInstUid = curCapabilityInst.getUniqueId();
-
- log.debug("Before getting all property values of capability instance {} of component istance {}.", curCapInstUid, componentInstanceId);
- Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> getOverridedPropertyValuesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curCapabilityInst.getLabel())),
- curCapInstUid, GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class);
- if (getOverridedPropertyValuesRes.isRight()) {
- error = getOverridedPropertyValuesRes.right().value();
- log.debug("Failed to retrieve property values of capability instance {}. Status is {}", curCapInstUid, error);
- } else {
- log.debug("After getting all property values of capability instance {} of component istance {}. Status is {}", curCapInstUid, componentInstanceId, error);
- Map<String, PropertyValueData> overridedPropertyValuesHM = new HashMap<>();
- List<ImmutablePair<PropertyValueData, GraphEdge>> overridedPropertyValues = getOverridedPropertyValuesRes.left().value();
- for (ImmutablePair<PropertyValueData, GraphEdge> curPropertyValuePair : overridedPropertyValues) {
- PropertyValueData curPropertyValue = curPropertyValuePair.getLeft();
- String propertyValueUid = curPropertyValue.getUniqueId();
- log.debug("Before getting property related to property value {} of capability instance {} of component istance {}.", propertyValueUid, curCapInstUid, componentInstanceId);
- Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> getPropertyDataRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curPropertyValue.getLabel())), propertyValueUid,
- GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class);
- if (getPropertyDataRes.isRight()) {
- error = getOverridedPropertyValuesRes.right().value();
- log.debug("Failed to retrieve property of property value {} Status is {}", propertyValueUid, error);
- }
- log.debug("After getting property related to property value {} of capability instance {} of component istance {}. Status is {}", propertyValueUid, curCapInstUid, componentInstanceId, error);
- PropertyData propertyData = getPropertyDataRes.left().value().getLeft();
- overridedPropertyValuesHM.put((String) propertyData.getUniqueId(), curPropertyValue);
- }
- overridedCapabilitiesHM.put((String) curCapabilityPair.getRight().getProperties().get(GraphPropertiesDictionary.CAPABILITY_ID.getProperty()), overridedPropertyValuesHM);
- }
- }
- }
- if (error == null && !overridedCapabilitiesHM.isEmpty()) {
- updateCapabilityPropertyValues(componentInstance.getCapabilities(), capabilityDefList, overridedCapabilitiesHM);
- }
- log.debug("After updating property values of capabilities of component istance {}. Status is {}", componentInstanceId, error);
- if (error == null) {
- return Either.left(capabilityDefList);
- }
- return Either.right(error);
- }
-
- private void updateCapabilityPropertyValues(Map<String, List<CapabilityDefinition>> capabilitiesOfRI, List<CapabilityDefinition> capabilitiesOfContainer, Map<String, Map<String, PropertyValueData>> overridedCapabilitiesHM) {
-
- capabilitiesOfContainer.stream().filter(capability -> overridedCapabilitiesHM.containsKey(capability.getUniqueId())).forEach(capability -> {
- boolean updateProperties = false;
- for (ComponentInstanceProperty property : capability.getProperties()) {
- if (overridedCapabilitiesHM.get(capability.getUniqueId()).containsKey(property.getUniqueId())) {
- property.setValue(overridedCapabilitiesHM.get(capability.getUniqueId()).get(property.getUniqueId()).getValue());
- property.setValueUniqueUid(overridedCapabilitiesHM.get(capability.getUniqueId()).get(property.getUniqueId()).getUniqueId());
- updateProperties = true;
- }
- }
- if (updateProperties) {
- capabilitiesOfRI.get(capability.getType()).get(0).setProperties(capability.getProperties());
- }
- });
- }
-
@Override
public Either<ComponentInstanceInput, StorageOperationStatus> updateInputValueInResourceInstance(ComponentInstanceInput input, String resourceInstanceId, boolean b) {
return null;
}
- public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId) {
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = artifactOperation.getArtifacts(componentInstanceId, NodeTypeEnum.ResourceInstance, true, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
- if (result.isRight() && result.right().value() == StorageOperationStatus.NOT_FOUND)
- return Either.right(StorageOperationStatus.OK);
- return result;
- }
-
@Override
public StorageOperationStatus updateCustomizationUUID(String componentInstanceId) {
Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId);
@@ -6080,75 +690,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
return StorageOperationStatus.OK;
}
- private Either<String, Boolean> handleGroupInstanceNameLogic(TitanVertex ciVertex, GroupInstance groupInstance, String componentInstanceId, String componentInstanceName, String groupName) {
-
- groupInstance.setGroupName(groupName);
-
- String logicalName = groupInstanceOperation.createGroupInstLogicalName(componentInstanceName, groupName);
-
- Boolean eitherValidation = validateGroupInstanceName(logicalName, groupInstance, true);
- if (!eitherValidation) {
- return Either.right(false);
- }
- // groupInstance.setName(logicalName);
- return Either.left(logicalName);
- }
-
- private Boolean validateGroupInstanceName(String groupInstanceName, GroupInstance groupInstance, boolean isCreate) {
-
- if (!ValidationUtils.validateStringNotEmpty(groupInstanceName)) {
- return false;
- }
- groupInstance.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(groupInstanceName));
- if (!isCreate) {
- if (!ValidationUtils.validateResourceInstanceNameLength(groupInstanceName)) {
- return false;
- }
- if (!ValidationUtils.validateResourceInstanceName(groupInstanceName)) {
- return false;
- }
- }
-
- return true;
-
- }
- // Evg: need to be public for reuse code in migration
- public Either<GroupInstance, StorageOperationStatus> createGroupInstance(TitanVertex ciVertex, GroupDefinition groupDefinition, ComponentInstance componentInstance) {
- // create VFC instance on VF
- GroupInstance groupInstance = null;
-
- boolean isCreateName = false;
- List<GroupInstance> groupInstances = componentInstance.getGroupInstances();
- if (groupInstances != null && !groupInstances.isEmpty()) {
- Optional<GroupInstance> op = groupInstances.stream().filter(p -> p.getGroupUid().equals(groupDefinition.getUniqueId())).findAny();
- if (op.isPresent()) {
- groupInstance = op.get();
-
- }
- }
- if (groupInstance == null) {
- groupInstance = new GroupInstance();
- groupInstance.setGroupUid(groupDefinition.getUniqueId());
-
- groupInstance.setArtifacts(groupDefinition.getArtifacts());
- Either<String, Boolean> handleNameLogic = handleGroupInstanceNameLogic(ciVertex, groupInstance, componentInstance.getUniqueId(), componentInstance.getNormalizedName(), groupDefinition.getName());
- if (handleNameLogic.isRight() && !handleNameLogic.right().value()) {
-
- if (handleNameLogic.isRight()) {
- log.debug("failed to create logical name gor group instance {}", groupInstance.getName());
- return Either.right(StorageOperationStatus.INVALID_ID);
-
- }
- }
- isCreateName = true;
- // groupInstance.setName(handleNameLogic.left().value());
-
- }
-
- return groupInstanceOperation.createGroupInstance(ciVertex, componentInstance.getUniqueId(), groupInstance, isCreateName);
-
- }
-
@Override
public Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java
deleted file mode 100644
index 9d9814efcb..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java
+++ /dev/null
@@ -1,2964 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import java.time.Duration;
-import java.time.Instant;
-import java.util.*;
-import java.util.Map.Entry;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.function.Function;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.commons.lang3.tuple.ImmutableTriple;
-import org.apache.commons.lang3.tuple.Pair;
-import org.apache.tinkerpop.gremlin.structure.Direction;
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
-import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.QueryType;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.category.GroupingDataDefinition;
-import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceInput;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DataTypeDefinition;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
-import org.openecomp.sdc.be.model.cache.ComponentCache;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.GroupingDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation;
-import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
-import org.openecomp.sdc.be.model.operations.api.ICapabilityOperation;
-import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.api.IRequirementOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator;
-import org.openecomp.sdc.be.resources.data.ArtifactData;
-import org.openecomp.sdc.be.resources.data.CapabilityData;
-import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
-import org.openecomp.sdc.be.resources.data.ProductMetadataData;
-import org.openecomp.sdc.be.resources.data.RequirementData;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
-import org.openecomp.sdc.be.resources.data.TagData;
-import org.openecomp.sdc.be.resources.data.UniqueIdData;
-import org.openecomp.sdc.be.resources.data.UserData;
-import org.openecomp.sdc.be.resources.data.category.CategoryData;
-import org.openecomp.sdc.be.resources.data.category.GroupingData;
-import org.openecomp.sdc.be.resources.data.category.SubCategoryData;
-import org.openecomp.sdc.be.utils.CommonBeUtils;
-import org.openecomp.sdc.be.workers.Job;
-import org.openecomp.sdc.be.workers.Manager;
-import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
-import org.openecomp.sdc.common.util.StreamUtils;
-import org.openecomp.sdc.common.util.ValidationUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import com.google.common.collect.ImmutableSet;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanGraphQuery;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-public abstract class ComponentOperation {
- private static Logger log = LoggerFactory.getLogger(ComponentOperation.class.getName());
-
- @Autowired
- protected TitanGenericDao titanGenericDao;
-
- @Autowired
- protected IArtifactOperation artifactOperation;
-
- @Autowired
- protected IElementOperation elementOperation;
-
- @Autowired
- protected ICapabilityOperation capabilityOperation;
-
- @Autowired
- protected IRequirementOperation requirementOperation;
-
- @Autowired
- protected ComponentInstanceOperation componentInstanceOperation;
-
- @Autowired
- private PropertyOperation propertyOperation;
-
- @Autowired
- protected InputsOperation inputOperation;
-
- @Autowired
- protected IAdditionalInformationOperation additionalInformationOperation;
-
- @Autowired
- protected GroupOperation groupOperation;
-
- @Autowired
- protected InputsOperation inputsOperation;
-
- @Autowired
- protected ApplicationDataTypeCache applicationDataTypeCache;
-
- @Autowired
- private ComponentCache componentCache;
-
- @Autowired
- private ToscaDefinitionPathCalculator toscaDefinitionPathCalculator;
-
- private static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1");
-
- protected Gson prettyJson = new GsonBuilder().setPrettyPrinting().create();
-
- protected Either<List<TagData>, StorageOperationStatus> createNewTagsList(List<String> tags) {
-
- List<TagData> existingTags = new ArrayList<TagData>();
- List<TagData> tagsToCreate = new ArrayList<TagData>();
- Either<List<TagData>, TitanOperationStatus> either = titanGenericDao.getAll(NodeTypeEnum.Tag, TagData.class);
-
- if ((either.isRight()) && (either.right().value() != TitanOperationStatus.NOT_FOUND)) {
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- } else if (either.isLeft()) {
- existingTags = either.left().value();
- }
-
- for (String tagName : tags) {
- TagData tag = new TagData(tagName);
- if ((existingTags == null) || (!existingTags.contains(tag))) {
- tagsToCreate.add(tag);
- }
- }
- return Either.left(tagsToCreate);
-
- }
-
- protected StorageOperationStatus createTagNodesOnGraph(List<TagData> tagsToCreate) {
- StorageOperationStatus result = StorageOperationStatus.OK;
- // In order to avoid duplicate tags
- tagsToCreate = ImmutableSet.copyOf(tagsToCreate).asList();
- if (tagsToCreate != null && false == tagsToCreate.isEmpty()) {
- for (TagData tagData : tagsToCreate) {
- log.debug("Before creating tag {}" , tagData);
- Either<TagData, TitanOperationStatus> createTagResult = titanGenericDao.createNode(tagData, TagData.class);
- if (createTagResult.isRight()) {
- TitanOperationStatus status = createTagResult.right().value();
- log.error("Cannot create {} in the graph. status is {}", tagData, status);
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
-
- }
- log.debug("After creating tag {}", tagData);
- }
- }
- return result;
- }
-
- public Either<Component, StorageOperationStatus> getLatestComponentByUuid(NodeTypeEnum nodeType, String uuid) {
- Either<Component, StorageOperationStatus> getComponentResult = null;
- Either<ComponentMetadataData, StorageOperationStatus> latestComponentMetadataRes = getLatestComponentMetadataByUuid(nodeType, uuid, false);
- if (latestComponentMetadataRes.isRight()) {
- getComponentResult = Either.right(latestComponentMetadataRes.right().value());
- }
- if (getComponentResult == null) {
- ComponentMetadataData latestVersion = latestComponentMetadataRes.left().value();
- String id = latestVersion.getMetadataDataDefinition().getUniqueId();
- Either<Component, StorageOperationStatus> component = getComponent(id, false);
- if (component.isRight()) {
- log.debug("Couldn't fetch component with type {} and id {}, error: {}", nodeType, id, component.right().value());
- getComponentResult = Either.right(component.right().value());
- } else {
- getComponentResult = Either.left(component.left().value());
- }
- }
- return getComponentResult;
- }
-
- public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(NodeTypeEnum nodeType, String uuid, boolean inTransaction) {
-
- Either<ComponentMetadataData, StorageOperationStatus> getComponentResult = null;
- List<ComponentMetadataData> latestVersionList = null;
- ComponentMetadataData latestVersion = null;
-
- Map<String, Object> propertiesToMatch = new HashMap<String, Object>();
- propertiesToMatch.put(GraphPropertiesDictionary.UUID.getProperty(), uuid);
- propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
- try{
- Either<List<ComponentMetadataData>, TitanOperationStatus> getComponentEither = titanGenericDao.getByCriteria(nodeType, propertiesToMatch, ComponentMetadataData.class);
- if (getComponentEither.isRight()) {
- log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", nodeType, uuid, getComponentEither.right().value());
- getComponentResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentEither.right().value()));
-
- }
- if (getComponentResult == null) {
- latestVersionList = getComponentEither.left().value();
- if (latestVersionList.isEmpty()) {
- log.debug("Component with type {} and uuid {} was not found", nodeType, uuid);
- getComponentResult = Either.right(StorageOperationStatus.NOT_FOUND);
- }
- }
- if (getComponentResult == null) {
- latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
- : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
- getComponentResult = Either.left(latestVersion);
- }
- } catch (Exception e){
- log.debug("Failed to get latest component metadata with type {} by uuid {}. ", nodeType.getName(), uuid, e);
- }finally {
- if (!inTransaction) {
- titanGenericDao.commit();
- }
- }
- return getComponentResult;
- }
-
- public <T extends GraphNode> Either<T, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, NodeTypeEnum nodeType, Class<T> clazz) {
-
- Map<String, Object> propertiesToMatch = new HashMap<String, Object>();
- propertiesToMatch.put(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId);
- Either<List<T>, TitanOperationStatus> getResponse = titanGenericDao.getByCriteria(nodeType, propertiesToMatch, clazz);
- if (getResponse.isRight()) {
- log.debug("Couldn't fetch component with type {} and unique id {}, error: {}", nodeType, uniqueId, getResponse.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value()));
-
- }
- List<T> serviceDataList = getResponse.left().value();
- if (serviceDataList.isEmpty()) {
- log.debug("Component with type {} and unique id {} was not found", nodeType, uniqueId);
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- T serviceData = serviceDataList.get(0);
- return Either.left(serviceData);
- }
-
- /**
- *
- * @param component
- * @param uniqueId
- * @param nodeType
- * @return
- */
- protected TitanOperationStatus setComponentCreatorFromGraph(Component component, String uniqueId, NodeTypeEnum nodeType) {
- Either<ImmutablePair<UserData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.CREATOR, NodeTypeEnum.User, UserData.class);
- if (parentNode.isRight()) {
- return parentNode.right().value();
- }
-
- ImmutablePair<UserData, GraphEdge> value = parentNode.left().value();
- if (log.isDebugEnabled())
- log.debug("Found parent node {}", value);
- UserData userData = value.getKey();
- if (log.isDebugEnabled())
- log.debug("Build resource : set creator userId to {}", userData.getUserId());
- String fullName = buildFullName(userData);
- if (log.isDebugEnabled())
- log.debug("Build resource : set last modifier full name to {} ", fullName);
- component.setCreatorUserId(userData.getUserId());
- component.setCreatorFullName(fullName);
-
- return TitanOperationStatus.OK;
- }
-
- protected TitanOperationStatus setComponentLastModifierFromGraph(Component component, String uniqueId, NodeTypeEnum nodeType) {
-
- Either<ImmutablePair<UserData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.LAST_MODIFIER, NodeTypeEnum.User, UserData.class);
- if (parentNode.isRight()) {
- return parentNode.right().value();
- }
-
- ImmutablePair<UserData, GraphEdge> value = parentNode.left().value();
- if (log.isDebugEnabled())
- log.debug("Found parent node {}", value);
- UserData userData = value.getKey();
-
- if (log.isDebugEnabled())
- log.debug("Build resource : set last modifier userId to {}", userData.getUserId());
- String fullName = buildFullName(userData);
- if (log.isDebugEnabled())
- log.debug("Build resource : set last modifier full name to {}", fullName);
- component.setLastUpdaterUserId(userData.getUserId());
- component.setLastUpdaterFullName(fullName);
-
- return TitanOperationStatus.OK;
- }
-
- /**
- *
- * @param userData
- * @return
- */
- protected String buildFullName(UserData userData) {
-
- String fullName = userData.getFirstName();
- if (fullName == null) {
- fullName = "";
- } else {
- fullName = fullName + " ";
- }
- String lastName = userData.getLastName();
- if (lastName != null) {
- fullName += lastName;
- }
- return fullName;
- }
-
- protected Either<UserData, TitanOperationStatus> findUser(String userId) {
- String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User);
- Either<UserData, TitanOperationStatus> findUser = titanGenericDao.getNode(key, userId, UserData.class);
- return findUser;
- }
-
- protected Either<TitanVertex, TitanOperationStatus> findUserVertex(String userId) {
- String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User);
- return titanGenericDao.getVertexByProperty(key, userId);
- }
-
- protected Either<GroupingData, TitanOperationStatus> findGrouping(NodeTypeEnum nodeType, String groupingId) {
- String key = UniqueIdBuilder.getKeyByNodeType(nodeType);
- Either<GroupingData, TitanOperationStatus> findGrouping = titanGenericDao.getNode(key, groupingId, GroupingData.class);
- return findGrouping;
- }
-
- protected Either<SubCategoryData, TitanOperationStatus> findSubCategory(NodeTypeEnum nodeType, String subCategoryId) {
- String key = UniqueIdBuilder.getKeyByNodeType(nodeType);
- Either<SubCategoryData, TitanOperationStatus> findSubCategory = titanGenericDao.getNode(key, subCategoryId, SubCategoryData.class);
- return findSubCategory;
- }
-
- protected Either<CategoryData, TitanOperationStatus> findCategory(NodeTypeEnum nodeType, String categoryId) {
- String key = UniqueIdBuilder.getKeyByNodeType(nodeType);
- Either<CategoryData, TitanOperationStatus> findCategory = titanGenericDao.getNode(key, categoryId, CategoryData.class);
- return findCategory;
- }
-
- protected TitanOperationStatus associateMetadataToComponent(ComponentMetadataData componentData, UserData userData, UserData updater, CategoryData categoryData, List<ResourceMetadataData> derivedResources) {
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.STATE.getProperty(), componentData.getMetadataDataDefinition().getState());
- Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.createRelation(updater, componentData, GraphEdgeLabels.STATE, props);
- log.debug("After associating user {} to component {}. Edge type is {}" , updater, componentData.getUniqueId(), GraphEdgeLabels.STATE);
- if (result.isRight()) {
- return result.right().value();
- }
-
- result = titanGenericDao.createRelation(updater, componentData, GraphEdgeLabels.LAST_MODIFIER, null);
- log.debug("After associating user {} to component {}. Edge type is {}", updater, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
- if (result.isRight()) {
- log.error("Failed to associate user {} to component {}. Edge type is {}", updater, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
- return result.right().value();
- }
-
- result = titanGenericDao.createRelation(userData, componentData, GraphEdgeLabels.CREATOR, null);
- log.debug("After associating user {} to component {}. Edge type is {}" , userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR);
- if (result.isRight()) {
- log.error("Failed to associate user {} to component {}. Edge type is {}", userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR);
- return result.right().value();
- }
-
- if (derivedResources != null) {
- for (ResourceMetadataData derivedResource : derivedResources) {
- log.debug("After associating component {} to parent component {}. Edge type is {}" ,componentData.getUniqueId(), derivedResource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM);
- result = titanGenericDao.createRelation(componentData, derivedResource, GraphEdgeLabels.DERIVED_FROM, null);
- if (result.isRight()) {
- log.error("Failed to associate user {} to component {}. Edge type is {}", userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR);
- return result.right().value();
- }
- }
- }
-
- if (categoryData != null) {
- result = titanGenericDao.createRelation(componentData, categoryData, GraphEdgeLabels.CATEGORY, null);
- log.debug("After associating component {} to category {}. Edge type is {}", componentData.getUniqueId(), categoryData, GraphEdgeLabels.CATEGORY);
- if (result.isRight()) {
- log.error("Faield to associate component {} to category {}. Edge type is {}", componentData.getUniqueId(), categoryData, GraphEdgeLabels.CATEGORY);
- return result.right().value();
- }
- }
-
- return TitanOperationStatus.OK;
- }
-
- protected StorageOperationStatus associateArtifactsToComponent(NodeTypeEnum nodeType, ComponentMetadataData componentData, Map<String, ArtifactDefinition> artifacts) {
-
- if (artifacts != null) {
- for (Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
-
- ArtifactDefinition artifactDefinition = entry.getValue();
- Either<ArtifactDefinition, StorageOperationStatus> addArifactToResource = Either.left(artifactDefinition);
- addArifactToResource = artifactOperation.addArifactToComponent(artifactDefinition, (String) componentData.getUniqueId(), nodeType, false, true);
- if (addArifactToResource.isRight()) {
- return addArifactToResource.right().value();
- }
- }
- }
- return StorageOperationStatus.OK;
-
- }
-
- protected Either<Boolean, StorageOperationStatus> validateResourceNameUniqueness(String name, Map<String, Object> hasProps, Map<String, Object> hasNotProps, TitanGenericDao titanGenericDao) {
- if (hasProps == null) {
- hasProps = new HashMap<String, Object>();
- }
- String normalizedName = ValidationUtils.normaliseComponentName(name);
- hasProps.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName);
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> resources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, hasProps, hasNotProps, ResourceMetadataData.class);
- if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("failed to get resources from graph with property name: {}", name);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
- }
- List<ResourceMetadataData> resourceList = (resources.isLeft() ? resources.left().value() : null);
- if (resourceList != null && resourceList.size() > 0) {
- if (log.isDebugEnabled()) {
- StringBuilder builder = new StringBuilder();
- for (ResourceMetadataData resourceData : resourceList) {
- builder.append(resourceData.getUniqueId() + "|");
- }
- log.debug("resources with property name:{} exists in graph. found {}",name, builder.toString());
- }
- return Either.left(false);
- } else {
- log.debug("resources with property name:{} does not exists in graph", name);
- return Either.left(true);
- }
-
- }
-
- protected Either<Boolean, StorageOperationStatus> validateServiceNameUniqueness(String name, TitanGenericDao titanGenericDao) {
- Map<String, Object> properties = new HashMap<>();
- String normalizedName = ValidationUtils.normaliseComponentName(name);
- properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName);
-
- Either<List<ServiceMetadataData>, TitanOperationStatus> services = titanGenericDao.getByCriteria(NodeTypeEnum.Service, properties, ServiceMetadataData.class);
- if (services.isRight() && services.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("failed to get services from graph with property name: {}" , name);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(services.right().value()));
- }
- List<ServiceMetadataData> serviceList = (services.isLeft() ? services.left().value() : null);
- if (serviceList != null && serviceList.size() > 0) {
- if (log.isDebugEnabled()) {
- StringBuilder builder = new StringBuilder();
- for (ServiceMetadataData serviceData : serviceList) {
- builder.append(serviceData.getUniqueId() + "|");
- }
- log.debug("Service with property name:{} exists in graph. found {}" , name, builder.toString());
- }
-
- return Either.left(false);
- } else {
- log.debug("Service with property name:{} does not exists in graph", name);
- return Either.left(true);
- }
- }
-
- protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name, TitanGenericDao titanGenericDao) {
- Map<String, Object> properties = new HashMap<>();
-
- properties.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), name);
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> resources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, properties, ResourceMetadataData.class);
- if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("failed to get resources from graph with property name: {}" , name);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
- }
- List<ResourceMetadataData> resourceList = (resources.isLeft() ? resources.left().value() : null);
- if (resourceList != null && resourceList.size() > 0) {
- if (log.isDebugEnabled()) {
- StringBuilder builder = new StringBuilder();
- for (ResourceMetadataData resourceData : resourceList) {
- builder.append(resourceData.getUniqueId() + "|");
- }
- log.debug("resources with property name:{} exists in graph. found {}" , name, builder.toString());
- }
- return Either.left(false);
- } else {
- log.debug("resources with property name:{} does not exists in graph", name);
- return Either.left(true);
- }
-
- }
-
- protected Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, TitanGenericDao titanGenericDao, NodeTypeEnum type) {
- Map<String, Object> properties = new HashMap<>();
- String normalizedName = ValidationUtils.normaliseComponentName(name);
- properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName);
-
- Either<List<ComponentMetadataData>, TitanOperationStatus> components = titanGenericDao.getByCriteria(type, properties, ComponentMetadataData.class);
- if (components.isRight() && components.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("failed to get components from graph with property name: {}" , name);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(components.right().value()));
- }
- List<ComponentMetadataData> componentList = (components.isLeft() ? components.left().value() : null);
- if (componentList != null && componentList.size() > 0) {
- if (log.isDebugEnabled()) {
- StringBuilder builder = new StringBuilder();
- for (ComponentMetadataData componentData : componentList) {
- builder.append(componentData.getUniqueId() + "|");
- }
- log.debug("Component with property name:{} exists in graph. found {}" , name, builder.toString());
- }
-
- return Either.left(false);
- } else {
- log.debug("Component with property name:{} does not exists in graph", name);
- return Either.left(true);
- }
- }
-
- protected StorageOperationStatus setArtifactFromGraph(String uniqueId, Component component, NodeTypeEnum type, IArtifactOperation artifactOperation) {
- StorageOperationStatus result = StorageOperationStatus.OK;
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(uniqueId, type, true);
- if (artifacts.isRight()) {
- result = artifacts.right().value();
- } else {
- // component.setArtifacts(artifacts.left().value());
- createSpecificArtifactList(component, artifacts.left().value());
- }
- return result;
- }
-
- protected Component createSpecificArtifactList(Component component, Map<String, ArtifactDefinition> artifacts) {
-
- if (artifacts != null) {
- Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
- Map<String, ArtifactDefinition> serviceApiArtifacts = new HashMap<>();
- Map<String, ArtifactDefinition> toscaArtifacts = new HashMap<>();
-
- Set<Entry<String, ArtifactDefinition>> specificet = new HashSet<>();
-
- for (Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
- ArtifactDefinition artifact = entry.getValue();
- ArtifactGroupTypeEnum artifactGroupType = artifact.getArtifactGroupType();
- if (artifactGroupType == null) {
- artifactGroupType = ArtifactGroupTypeEnum.INFORMATIONAL;
- }
-
- switch (artifactGroupType) {
- case DEPLOYMENT:
- deploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
- specificet.add(entry);
- break;
- case SERVICE_API:
- serviceApiArtifacts.put(artifact.getArtifactLabel(), artifact);
- specificet.add(entry);
- break;
- case TOSCA:
- toscaArtifacts.put(artifact.getArtifactLabel(), artifact);
- specificet.add(entry);
- break;
- default:
- break;
- }
-
- }
- artifacts.entrySet().removeAll(specificet);
-
- component.setSpecificComponetTypeArtifacts(serviceApiArtifacts);
- component.setDeploymentArtifacts(deploymentArtifacts);
- component.setToscaArtifacts(toscaArtifacts);
- component.setArtifacts(artifacts);
- }
- return component;
- }
-
- private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> collectComponents(TitanGraph graph, NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class<S> clazz, ResourceTypeEnum resourceType) {
- List<T> components = new ArrayList<>();
- Either<List<ImmutablePair<S, GraphEdge>>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz);
- if (parentNodes.isLeft()) {
- for (ImmutablePair<S, GraphEdge> component : parentNodes.left().value()) {
- ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition();
- Boolean isHighest = componentData.isHighestVersion();
- boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData);
-
- if (isHighest && isMatchingResourceType) {
- Either<T, StorageOperationStatus> result = getLightComponent(componentData.getUniqueId(), true);
- if (result.isRight()) {
- return Either.right(result.right().value());
- }
- components.add(result.left().value());
- }
- }
- }
- return Either.left(components);
- }
-
- private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType,
- ComponentMetadataDataDefinition componentData) {
-
- boolean isMatching;
- if (componentType == NodeTypeEnum.Resource) {
- if (resourceType == null) {
- isMatching = true;
- } else {
- isMatching = resourceType == ((ResourceMetadataDataDefinition)componentData).getResourceType();
- }
- } else {
- isMatching = true;
- }
- return isMatching;
- }
-
- protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction,
- Class<S> clazz, ResourceTypeEnum resourceType) {
- try {
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- if (graph.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
-
- }
- return collectComponents(graph.left().value(), neededType, categoryUid, categoryType, clazz, resourceType);
-
- } finally {
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- }
- }
-
- protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction,
- Class<S> clazz, ResourceTypeEnum resourceType) {
- List<T> components = new ArrayList<>();
- try {
- Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class;
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(categoryName));
- Either<List<GraphNode>, TitanOperationStatus> getCategory = titanGenericDao.getByCriteria(categoryType, props, categoryClazz);
- if (getCategory.isRight()) {
- return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
- }
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- if (graph.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
-
- }
- for (GraphNode category : getCategory.left().value()) {
- Either<List<T>, StorageOperationStatus> result = collectComponents(graph.left().value(), neededType, (String) category.getUniqueId(), categoryType, clazz, resourceType);
- if (result.isRight()) {
- return result;
- }
- components.addAll(result.left().value());
- }
-
- return Either.left(components);
- } finally {
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- }
- }
-
- <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTransaction, NodeTypeEnum neededType) {
- return null;
- }
-
- protected Either<List<Component>, StorageOperationStatus> getFollowedComponent(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction, TitanGenericDao titanGenericDao,
- NodeTypeEnum neededType) {
-
- Either<List<Component>, StorageOperationStatus> result = null;
-
- try {
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- if (graph.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
- return result;
- }
- Iterable<TitanVertex> users;
-
- if (userId == null) {
- // get all users by label
- // for Tester and Admin retrieve all users
-
- // users =
- // graph.left().value().getVertices(GraphPropertiesDictionary.LABEL.getProperty(),
- // NodeTypeEnum.User.getName());
- users = graph.left().value().query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.User.getName()).vertices();
-
- } else {
- // for Designer retrieve specific user
- String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User);
- users = graph.left().value().query().has(key, userId).vertices();
- }
- Iterator<TitanVertex> userIterator = users.iterator();
-
- List<Component> components = new ArrayList<>();
- while (userIterator.hasNext()) {
- Vertex vertexUser = userIterator.next();
-
- // get all resource with current state
- Iterator<Edge> iterator = vertexUser.edges(Direction.OUT, GraphEdgeLabels.STATE.getProperty());
-
- List<Component> componentsPerUser = fetchComponents(lifecycleStates, iterator, neededType, inTransaction);
-
- HashSet<String> ids = new HashSet<String>();
-
- if (componentsPerUser != null) {
- for (Component comp : componentsPerUser) {
- ids.add(comp.getUniqueId());
- components.add(comp);
- }
- }
-
- if (lastStateStates != null && !lastStateStates.isEmpty()) {
- // get all resource with last state
- iterator = vertexUser.edges(Direction.OUT, GraphEdgeLabels.LAST_STATE.getProperty());
- boolean isFirst;
- componentsPerUser = fetchComponents(lastStateStates, iterator, neededType, inTransaction);
- if (componentsPerUser != null) {
- for (Component comp : componentsPerUser) {
- isFirst = true;
-
- if (ids.contains(comp.getUniqueId())) {
- isFirst = false;
- }
- if (isFirst == true) {
- components.add(comp);
- }
-
- }
- }
- }
-
- } // whlile users
-
- result = Either.left(components);
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- titanGenericDao.rollback();
- } else {
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- private List<Component> fetchComponents(Set<LifecycleStateEnum> lifecycleStates, Iterator<Edge> iterator, NodeTypeEnum neededType, boolean inTransaction) {
- List<Component> components = new ArrayList<>();
- while (iterator.hasNext()) {
- Edge edge = iterator.next();
-
- String stateStr = edge.value(GraphEdgePropertiesDictionary.STATE.getProperty());
- LifecycleStateEnum state = LifecycleStateEnum.findState(stateStr);
- if (state == null) {
- log.debug("not supported STATE for element {}" , stateStr);
- continue;
- }
- if (lifecycleStates != null && lifecycleStates.contains(state)) {
- Vertex vertexComponent = edge.inVertex();
-
- Boolean isHighest = vertexComponent.value(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty());
- if (isHighest) {
-
- String nodeTypeStr = vertexComponent.value(GraphPropertiesDictionary.LABEL.getProperty());
- // get only latest versions
- NodeTypeEnum nodeType = NodeTypeEnum.getByName(nodeTypeStr);
-
- if (nodeType == null) {
- log.debug("missing node label for vertex {}", vertexComponent);
- continue;
- }
-
- if (neededType.equals(nodeType)) {
- switch (nodeType) {
- case Service:
- handleNode(components, vertexComponent, nodeType, inTransaction);
- break;
- case Resource:
- Boolean isAbtract = vertexComponent.value(GraphPropertiesDictionary.IS_ABSTRACT.getProperty());
- if (false == isAbtract) {
- handleNode(components, vertexComponent, nodeType, inTransaction);
- } // if not abstract
- break;
- case Product:
- handleNode(components, vertexComponent, nodeType, inTransaction);
- break;
- default:
- log.debug("not supported node type {}", nodeType);
- break;
- }// case
- } // needed type
- }
- } // if
- } // while resources
- return components;
- }
-
- protected <T> void handleNode(List<T> components, Vertex vertexComponent, NodeTypeEnum nodeType, boolean inTransaction) {
- String id;
-
- id = vertexComponent.value(UniqueIdBuilder.getKeyByNodeType(nodeType));
- if (id != null) {
- Either<T, StorageOperationStatus> component = getLightComponent(id, inTransaction);
- if (component.isRight()) {
- log.debug("Failed to get component for id = {} error : {} skip resource", id, component.right().value());
- } else {
- components.add(component.left().value());
- }
- } else {
-
- Map<String, Object> properties = this.titanGenericDao.getProperties(vertexComponent);
- log.debug("missing resource unique id for node with properties {}", properties);
- }
- }
-
- /**
- *
- * @param component
- * @param inTransaction
- * @param titanGenericDao
- * @param clazz
- * @return
- */
- public <T> Either<T, StorageOperationStatus> updateComponent(Component component, boolean inTransaction, TitanGenericDao titanGenericDao, Class<T> clazz, NodeTypeEnum type) {
-
- ComponentParametersView componentParametersView = new ComponentParametersView();
- return updateComponentFilterResult(component, inTransaction, titanGenericDao, clazz, type, componentParametersView);
-
- }
-
- private Either<ArtifactData, StorageOperationStatus> generateAndUpdateToscaFileName(String componentType, String componentName, String componentId, NodeTypeEnum type, ArtifactDefinition artifactInfo) {
- Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts().entrySet().stream()
- .filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel()))
- .findAny()
- .get()
- .getValue();
- artifactInfo.setArtifactName(componentType + "-" + componentName + getConfig.get("artifactName"));
- return artifactOperation.updateToscaArtifactNameOnGraph(artifactInfo, artifactInfo.getUniqueId(), type, componentId);
- }
-
- protected StorageOperationStatus moveCategoryEdge(Component component, ComponentMetadataData componentData, CategoryDefinition newCategory, NodeTypeEnum type) {
-
- StorageOperationStatus result = StorageOperationStatus.OK;
-
- GraphRelation categoryRelation = new GraphRelation();
- categoryRelation.setType(GraphEdgeLabels.CATEGORY.getProperty());
- RelationEndPoint relationEndPoint = new RelationEndPoint(type, UniqueIdBuilder.getKeyByNodeType(type), component.getUniqueId());
- categoryRelation.setFrom(relationEndPoint);
- Either<GraphRelation, TitanOperationStatus> deleteOutgoingRelation = titanGenericDao.deleteOutgoingRelation(categoryRelation);
- if (deleteOutgoingRelation.isRight()) {
- log.error("Failed to delete category from component {}. Edge type is {}", componentData.getUniqueId(), GraphEdgeLabels.CATEGORY);
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteOutgoingRelation.right().value());
- return result;
- }
-
- log.debug("After removing edge from graph {}", deleteOutgoingRelation);
-
- NodeTypeEnum categoryType;
- if (NodeTypeEnum.Service.name().equalsIgnoreCase(type.name())) {
- categoryType = NodeTypeEnum.ServiceCategory;
- } else {
- categoryType = NodeTypeEnum.ResourceCategory;
- }
- Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(newCategory.getName(), NodeTypeEnum.ServiceNewCategory, CategoryData.class);
- if (categoryResult.isRight()) {
- StorageOperationStatus status = categoryResult.right().value();
- log.error("Cannot find category {} in the graph. status is {}", newCategory.getName(), status);
- return status;
- }
-
- CategoryData categoryData = categoryResult.left().value();
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(componentData, categoryData, GraphEdgeLabels.CATEGORY, null);
- log.debug("After associating category {} to component {}. Edge type is {}", categoryData, componentData.getUniqueId(), GraphEdgeLabels.CATEGORY);
- if (createRelation.isRight()) {
- log.error("Failed to associate category {} to component {}. Edge type is {}", categoryData, componentData.getUniqueId(), GraphEdgeLabels.CATEGORY);
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value());
- return result;
- }
-
- return result;
- }
-
- private StorageOperationStatus moveLastModifierEdge(Component component, ComponentMetadataData componentData, UserData modifierUserData, NodeTypeEnum type) {
-
- StorageOperationStatus result = StorageOperationStatus.OK;
-
- GraphRelation lastModifierRelation = new GraphRelation();
- lastModifierRelation.setType(GraphEdgeLabels.LAST_MODIFIER.getProperty());
- RelationEndPoint relationEndPoint = new RelationEndPoint(type, UniqueIdBuilder.getKeyByNodeType(type), component.getUniqueId());
- lastModifierRelation.setTo(relationEndPoint);
- Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = titanGenericDao.deleteIncomingRelation(lastModifierRelation);
- if (deleteIncomingRelation.isRight()) {
- log.error("Failed to delete user from component {}. Edge type is {}", componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteIncomingRelation.right().value());
- return result;
- }
-
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(modifierUserData, componentData, GraphEdgeLabels.LAST_MODIFIER, null);
- log.debug("After associating user {} to component {}. Edge type is {}", modifierUserData, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
- if (createRelation.isRight()) {
- log.error("Failed to associate user {} to component {}. Edge type is {}", modifierUserData, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value());
- return result;
- }
- return result;
- }
-
- protected abstract ComponentMetadataData getMetaDataFromComponent(Component component);
-
- public abstract <T> Either<T, StorageOperationStatus> getComponent(String id, boolean inTransaction);
-
- public abstract <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTrasnaction);
-
- protected abstract <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction);
-
- public abstract <T> Either<T, StorageOperationStatus> getLightComponent(String id, boolean inTransaction);
-
- public abstract <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTransaction);
-
- abstract Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData);
-
- abstract TitanOperationStatus setComponentCategoriesFromGraph(Component component);
-
- protected abstract Either<Component, StorageOperationStatus> getMetadataComponent(String id, boolean inTransaction);
-
- protected abstract <T> Either<T, StorageOperationStatus> updateComponent(T component, boolean inTransaction);
-
- protected abstract <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterParametersView);
-
- public abstract Either<Component, StorageOperationStatus> deleteComponent(String id, boolean inTransaction);
-
- public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, boolean inTransaction) {
- return cloneComponent(other, version, null, inTransaction);
- }
-
- public abstract <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction);
-
- public abstract Component getDefaultComponent();
-
- public abstract boolean isComponentExist(String componentId);
-
- public abstract Either<Boolean, StorageOperationStatus> validateComponentNameExists(String componentName);
-
- public abstract Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId);
-
- protected Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId, NodeTypeEnum nodeType) {
-
- Either<GraphRelation, TitanOperationStatus> relationByCriteria = titanGenericDao.getIncomingRelationByCriteria(new UniqueIdData(nodeType, componentId), GraphEdgeLabels.INSTANCE_OF, null);
- if (relationByCriteria.isRight() && !relationByCriteria.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("failed to check relations for component node. id = {}, type = {}, error = {}", componentId, nodeType, relationByCriteria.right().value().name());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(relationByCriteria.right().value()));
- }
-
- if (relationByCriteria.isLeft()) {
- // component is in use
- return Either.left(true);
- } else {
- return Either.left(false);
- }
-
- }
-
- public abstract Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion();
-
- protected Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(NodeTypeEnum nodeType) {
-
- List<String> componentIdsToDelete = new ArrayList<String>();
- // get all components marked for delete
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.IS_DELETED.getProperty(), true);
-
- Either<List<ComponentMetadataData>, TitanOperationStatus> componentsToDelete = titanGenericDao.getByCriteria(nodeType, props, ComponentMetadataData.class);
-
- if (componentsToDelete.isRight()) {
- TitanOperationStatus error = componentsToDelete.right().value();
- if (error.equals(TitanOperationStatus.NOT_FOUND)) {
- log.trace("no components to delete");
- return Either.left(componentIdsToDelete);
- } else {
- log.info("failed to find components to delete. error : {}", error.name());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error));
- }
-
- }
- for (ComponentMetadataData resourceData : componentsToDelete.left().value()) {
- componentIdsToDelete.add(resourceData.getMetadataDataDefinition().getUniqueId());
- }
- return Either.left(componentIdsToDelete);
- }
-
- protected <T extends GraphNode> Either<List<T>, TitanOperationStatus> __getLastVersion(NodeTypeEnum type, Map<String, Object> props, Class<T> clazz) {
- try {
-
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- if (graph.isRight()) {
- return Either.right(graph.right().value());
- }
-
- TitanGraph tGraph = graph.left().value();
- TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query();
- query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), type.getName());
-
- if (props != null && !props.isEmpty()) {
- for (Map.Entry<String, Object> entry : props.entrySet()) {
- query = query.hasNot(entry.getKey(), entry.getValue());
- }
- }
- query.has(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
-
- Iterable<TitanVertex> vertices = query.vertices();
-
- if (vertices == null) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- Iterator<TitanVertex> iterator = vertices.iterator();
- List<T> result = new ArrayList<T>();
-
- while (iterator.hasNext()) {
- Vertex vertex = iterator.next();
-
- Map<String, Object> newProp = titanGenericDao.getProperties(vertex);
- T element = GraphElementFactory.createElement(type.getName(), GraphElementTypeEnum.Node, newProp, clazz);
- result.add(element);
- }
- if (result.size() == 0) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
- log.debug("No nodes in graph for criteria : from type = {} and properties = {}", type, props);
- return Either.left(result);
- } catch (Exception e) {
- log.debug("Failed get by criteria for type = {} and properties = {}", type, props, e);
- return Either.right(TitanGraphClient.handleTitanException(e));
- }
- }
-
- protected <T extends GraphNode> Either<List<T>, TitanOperationStatus> getLastVersion(NodeTypeEnum type, Map<String, Object> hasNotProps, Class<T> clazz) {
- return getLastVersion(type, null, hasNotProps, clazz);
- }
-
- protected <T extends GraphNode> Either<List<T>, TitanOperationStatus> getLastVersion(NodeTypeEnum type, Map<String, Object> hasProps, Map<String, Object> hasNotProps, Class<T> clazz) {
-
- Map<String, Object> props = new HashMap<>();
-
- if (hasProps != null) {
- props.putAll(hasProps);
- }
- props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
-
- Either<List<T>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(type, props, hasNotProps, clazz);
-
- return byCriteria;
-
- }
-
- public <T, S extends GraphNode> Either<Set<T>, StorageOperationStatus> getComponentCatalogData(NodeTypeEnum type, Map<String, Object> propertiesToMatch, Class<T> clazz1, Class<S> clazz2, boolean inTransaction) {
- log.debug("Start getComponentCatalogData for type: {}", type.name());
- Set<T> result = new HashSet<T>();
- Either<List<S>, TitanOperationStatus> lastVersionNodes = getLastVersion(type, propertiesToMatch, clazz2);
- Either<Set<T>, StorageOperationStatus> last = retrieveComponentsFromNodes(lastVersionNodes, inTransaction);
- if (last.isLeft() && last.left().value() != null) {
- result.addAll(last.left().value());
- }
- if (type == NodeTypeEnum.Resource) {
- propertiesToMatch.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), false);
- }
- Either<List<S>, TitanOperationStatus> componentsNodes = titanGenericDao.getByCriteria(type, propertiesToMatch, clazz2);
- Either<Set<T>, StorageOperationStatus> certified = retrieveComponentsFromNodes(componentsNodes, inTransaction);
- if (certified.isLeft() && certified.left().value() != null) {
- result.addAll(certified.left().value());
- }
- return Either.left(result);
-
- }
-
- protected <T, S extends GraphNode> Either<Set<T>, StorageOperationStatus> retrieveComponentsFromNodes(Either<List<S>, TitanOperationStatus> componentsNodes, boolean inTransaction) {
- Set<T> result = new HashSet<T>();
- if (componentsNodes.isRight()) {
- // in case of NOT_FOUND from Titan client return to UI empty list
- if (componentsNodes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- log.debug("No components were found");
- } else {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentsNodes.right().value()));
- }
- } else {
- List<S> componentDataList = componentsNodes.left().value();
- for (S componentData : componentDataList) {
- // Either<T, StorageOperationStatus> component =
- // getComponent((String) componentData.getUniqueId(),
- // inTransaction);
- Either<T, StorageOperationStatus> component = getLightComponent((String) componentData.getUniqueId(), inTransaction);
- if (component.isRight()) {
- log.debug("Failed to get component for id = {} error : {} skip resource", componentData.getUniqueId(), component.right().value());
- // return Either.right(service.right().value());
- } else {
- result.add(component.left().value());
- }
- }
- }
- return Either.left(result);
- }
-
- protected StorageOperationStatus removeArtifactsFromComponent(Component component, NodeTypeEnum componentType) {
-
- String componentId = component.getUniqueId();
- // Map<String, ArtifactDefinition> artifacts = component.getArtifacts();
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsRes = artifactOperation.getArtifacts(componentId, componentType, true);
- if (artifactsRes.isRight() && !artifactsRes.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- return artifactsRes.right().value();
- }
- if (artifactsRes.isLeft() && artifactsRes.left().value() != null) {
- Map<String, ArtifactDefinition> artifacts = artifactsRes.left().value();
- for (Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
-
- ArtifactDefinition artifactDefinition = entry.getValue();
- Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource = artifactOperation.removeArifactFromResource(componentId, artifactDefinition.getUniqueId(), componentType, true, true);
- if (removeArifactFromResource.isRight()) {
- return removeArifactFromResource.right().value();
- }
- }
- }
- return StorageOperationStatus.OK;
- }
-
- public Either<List<Component>, StorageOperationStatus> getTesterFollowedComponent(String userId, Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction, NodeTypeEnum neededType) {
- List<Component> resList = new ArrayList<>();
- Either<List<Component>, StorageOperationStatus> rip = getFollowedComponent(userId, lifecycleStates, null, inTransaction, titanGenericDao, neededType);
- if (rip.isLeft()) {
- List<Component> ripRes = rip.left().value();
- if (ripRes != null && !ripRes.isEmpty()) {
- resList.addAll(ripRes);
- }
- Set<LifecycleStateEnum> rfcState = new HashSet<>();
- rfcState.add(LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<List<Component>, StorageOperationStatus> rfc = getFollowedComponent(null, rfcState, null, inTransaction, titanGenericDao, neededType);
- if (rfc.isLeft()) {
- List<Component> rfcRes = rfc.left().value();
- if (rfcRes != null && !rfcRes.isEmpty()) {
- resList.addAll(rfcRes);
- }
- } else {
- return Either.right(rfc.right().value());
- }
-
- } else {
- return Either.right(rip.right().value());
- }
- return Either.left(resList);
-
- }
-
- /**
- * generate UUID only for case that version is "XX.01" - (start new version)
- *
- * @param component
- */
- protected void generateUUID(Component component) {
- String version = component.getVersion();
- if (uuidNewVersion.matcher(version).matches()) {
- UUID uuid = UUID.randomUUID();
- component.getComponentMetadataDefinition().getMetadataDataDefinition().setUUID(uuid.toString());
- MDC.put("serviceInstanceID", uuid.toString());
- }
- }
-
- protected <T extends GraphNode> Either<Map<String, String>, TitanOperationStatus> getVersionList(NodeTypeEnum type, String version, Component component, Class<T> clazz) {
- return getVersionList(type, version, component.getUUID(), component.getSystemName(), clazz);
- }
-
- protected <T extends GraphNode> Either<Map<String, String>, TitanOperationStatus> getVersionList(NodeTypeEnum type, String version, String uuid, String systemName, Class<T> clazz) {
- Map<String, Object> props = new HashMap<String, Object>();
- Map<String, Object> hasNotProps = new HashMap<String, Object>();
-
- if (version.startsWith("0")) {
- props.put(GraphPropertiesDictionary.UUID.getProperty(), uuid);
- } else {
- props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), systemName);
- }
- hasNotProps.put(GraphPropertiesDictionary.IS_DELETED.getProperty(), true);
- Either<List<T>, TitanOperationStatus> result = titanGenericDao.getByCriteria(type, props, hasNotProps, clazz);
-
- Map<String, String> versionMap = new HashMap<String, String>();
- if (result.isRight()) {
- if (!result.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- return Either.right(result.right().value());
- }
-
- } else {
- switch (type) {
- case Resource:
- List<ResourceMetadataData> components = (List<ResourceMetadataData>) result.left().value();
- for (ResourceMetadataData data : components) {
- versionMap.put(data.getMetadataDataDefinition().getVersion(), (String) data.getUniqueId());
- }
- break;
- case Service:
- List<ServiceMetadataData> componentsS = (List<ServiceMetadataData>) result.left().value();
- for (ServiceMetadataData data : componentsS) {
- versionMap.put(data.getMetadataDataDefinition().getVersion(), (String) data.getUniqueId());
- }
- break;
- case Product:
- List<ProductMetadataData> componentsP = (List<ProductMetadataData>) result.left().value();
- for (ProductMetadataData data : componentsP) {
- versionMap.put(data.getMetadataDataDefinition().getVersion(), (String) data.getUniqueId());
- }
- break;
- default:
- break;
- }
- }
-
- return Either.left(versionMap);
- }
-
- protected StorageOperationStatus deleteAdditionalInformation(NodeTypeEnum nodeType, String componentId) {
-
- Either<AdditionalInformationDefinition, StorageOperationStatus> deleteRes = additionalInformationOperation.deleteAllAdditionalInformationParameters(nodeType, componentId, true);
-
- if (deleteRes.isRight()) {
- StorageOperationStatus status = deleteRes.right().value();
- return status;
- }
-
- return StorageOperationStatus.OK;
-
- }
-
- protected StorageOperationStatus addAdditionalInformation(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition informationDefinition) {
-
- Either<AdditionalInformationDefinition, TitanOperationStatus> status = additionalInformationOperation.addAdditionalInformationNode(nodeType, componentId, informationDefinition);
-
- if (status.isRight()) {
- TitanOperationStatus titanStatus = status.right().value();
- return DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
- }
-
- log.trace("After adding additional information to component {}. Result is {}" , componentId ,status.left().value());
-
- return StorageOperationStatus.OK;
-
- }
-
- protected StorageOperationStatus addAdditionalInformation(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition informationDefinition, TitanVertex metadataVertex) {
-
- TitanOperationStatus status = additionalInformationOperation.addAdditionalInformationNode(nodeType, componentId, informationDefinition, metadataVertex);
- log.trace("After adding additional information to component {}. Result is {}", componentId, status);
-
- if (!status.equals(TitanOperationStatus.OK)) {
- return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- }
-
- return StorageOperationStatus.OK;
-
- }
-
- public Either<List<ArtifactDefinition>, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType, boolean inTransacton) {
- List<ArtifactDefinition> artifacts = new ArrayList<ArtifactDefinition>();
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse = artifactOperation.getArtifacts(parentId, parentType, inTransacton);
- if (artifactsResponse.isRight()) {
- if (!artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- log.debug("failed to retrieve artifacts for {} {}", parentType, parentId);
- return Either.right(artifactsResponse.right().value());
- }
- } else {
- artifacts.addAll(artifactsResponse.left().value().values());
- }
-
- if (NodeTypeEnum.Resource.equals(parentType)) {
- Either<List<ArtifactDefinition>, StorageOperationStatus> interfacesArtifactsForResource = getAdditionalArtifacts(parentId, false, true);
- if (artifactsResponse.isRight() && !interfacesArtifactsForResource.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
- log.debug("failed to retrieve interface artifacts for {} {}", parentType, parentId);
- return Either.right(interfacesArtifactsForResource.right().value());
- } else if (artifactsResponse.isLeft()) {
- artifacts.addAll(interfacesArtifactsForResource.left().value());
- }
- }
- return Either.left(artifacts);
- }
-
- protected void addComponentInternalFields(ComponentMetadataData componentMetadataData) {
- org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition metadataDataDefinition = componentMetadataData.getMetadataDataDefinition();
- Long creationDate = metadataDataDefinition.getCreationDate();
-
- long currentDate = System.currentTimeMillis();
- if (creationDate == null) {
- metadataDataDefinition.setCreationDate(currentDate);
- }
- metadataDataDefinition.setLastUpdateDate(currentDate);
-
- String lifecycleStateEnum = metadataDataDefinition.getState();
- if (lifecycleStateEnum == null) {
- metadataDataDefinition.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
- }
- String componentUniqueId = UniqueIdBuilder.buildComponentUniqueId();
- metadataDataDefinition.setUniqueId(componentUniqueId);
- metadataDataDefinition.setHighestVersion(true);
- }
-
- protected StorageOperationStatus createTagsForComponent(Component component) {
- List<String> tags = component.getTags();
- if (tags != null && false == tags.isEmpty()) {
- Either<List<TagData>, StorageOperationStatus> tagsResult = createNewTagsList(tags);
-
- if (tagsResult == null) {
- log.debug("tagsResult is null");
- return StorageOperationStatus.GENERAL_ERROR;
- }
- if (tagsResult.isRight()) {
- return tagsResult.right().value();
- }
- List<TagData> tagsToCreate = tagsResult.left().value();
- return createTagNodesOnGraph(tagsToCreate);
- }
- log.trace("All tags created succesfully for component {}", component.getUniqueId());
- return StorageOperationStatus.OK;
- }
-
- protected Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent(NodeTypeEnum nodeTypeEnum, Component component) {
- List<CategoryDefinition> categories = component.getCategories();
- List<GroupingData> groupingDataToAssociate = new ArrayList<>();
- if (categories != null) {
- groupingDataToAssociate = new ArrayList<>();
- for (CategoryDefinition categoryDefinition : categories) {
- List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories();
- if (subcategories != null) {
- for (SubCategoryDefinition subCategoryDefinition : subcategories) {
- List<GroupingDefinition> groupingDataDefinitions = subCategoryDefinition.getGroupings();
- if (groupingDataDefinitions != null) {
- for (GroupingDataDefinition grouping : groupingDataDefinitions) {
- String groupingId = grouping.getUniqueId();
- Either<GroupingData, TitanOperationStatus> findGroupingEither = findGrouping(nodeTypeEnum, groupingId);
- if (findGroupingEither.isRight()) {
- TitanOperationStatus status = findGroupingEither.right().value();
- log.error("Cannot find grouping {} in the graph. status is {}", groupingId, status);
- if (status == TitanOperationStatus.NOT_FOUND) {
- return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
- }
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- } else {
- groupingDataToAssociate.add(findGroupingEither.left().value());
- }
- }
- }
- }
- }
- }
- }
- return Either.left(groupingDataToAssociate);
- }
-
- protected TitanOperationStatus associateGroupingsToComponent(ComponentMetadataData componentMetadataData, List<GroupingData> groupingDataToAssociate) {
- for (GroupingData groupingData : groupingDataToAssociate) {
- GraphEdgeLabels groupingLabel = GraphEdgeLabels.GROUPING;
- Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.createRelation(componentMetadataData, groupingData, groupingLabel, null);
- log.debug("After associating grouping {} to component {}. Edge type is {}", groupingData, componentMetadataData, groupingLabel);
- if (result.isRight()) {
- return result.right().value();
- }
- }
- log.trace("All groupings associated succesfully to component {}", componentMetadataData);
- return TitanOperationStatus.OK;
- }
-
- public abstract Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction);
-
- protected Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, NodeTypeEnum nodeType, boolean inTransaction) {
- Either<Integer, StorageOperationStatus> result = null;
- try {
-
- Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
- if (graphResult.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
- return result;
- }
- Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId);
- if (vertexService.isRight()) {
- log.debug("failed to fetch vertex of component metadata, nodeType:{} , id: {}", nodeType, componentId);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value()));
- return result;
- }
- Vertex vertex = vertexService.left().value();
- Integer instanceCounter = vertex.value(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty());
- ++instanceCounter;
- vertex.property(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty(), instanceCounter);
- result = Either.left(instanceCounter);
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("increaseAndGetComponentInstanceCounter operation : Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("increaseAndGetComponentInstanceCounter operation : Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- protected Either<Integer, StorageOperationStatus> setComponentInstanceCounter(String componentId, NodeTypeEnum nodeType, int counter, boolean inTransaction) {
- Either<Integer, StorageOperationStatus> result = null;
- try {
-
- Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
- if (graphResult.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
- return result;
- }
- Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId);
- if (vertexService.isRight()) {
- log.debug("failed to fetch vertex of component metadata ofor id = {}", componentId);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value()));
- return result;
- }
- Vertex vertex = vertexService.left().value();
- vertex.property(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty(), counter);
- result = Either.left(counter);
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("deleteService operation : Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("deleteService operation : Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- protected TitanOperationStatus setComponentInstancesFromGraph(String uniqueId, Component component, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType) {
-
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resourceInstancesOfService = componentInstanceOperation.getComponentInstancesOfComponent(uniqueId, containerNodeType, compInstNodeType);
-
- if (resourceInstancesOfService.isRight()) {
- TitanOperationStatus status = resourceInstancesOfService.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.OK;
- } else {
- log.error("Failed to fetch resource instances and their relations. status is {}", status);
- }
- return status;
- }
-
- ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>> immutablePair = resourceInstancesOfService.left().value();
- List<ComponentInstance> instances = immutablePair.getKey();
- List<RequirementCapabilityRelDef> relations = immutablePair.getValue();
-
- component.setComponentInstances(instances);
- component.setComponentInstancesRelations(relations);
-
- return TitanOperationStatus.OK;
- }
-
- /**
- * set all properties of all of its resources
- *
- * @param uniqueId
- * @return
- */
- protected TitanOperationStatus ___setComponentInstancesPropertiesFromGraph(String uniqueId, Component component) {
-
- List<ComponentInstance> resourceInstances = component.getComponentInstances();
-
- Map<String, List<ComponentInstanceProperty>> resourceInstancesProperties = new HashMap<>();
-
- Map<String, List<PropertyDefinition>> alreadyProcessedResources = new HashMap<>();
-
- if (resourceInstances != null) {
- for (ComponentInstance resourceInstance : resourceInstances) {
-
- log.debug("Going to update properties of resource instance {}", resourceInstance.getUniqueId());
- String resourceUid = resourceInstance.getComponentUid();
-
- List<PropertyDefinition> properties = alreadyProcessedResources.get(resourceUid);
- if (properties == null) {
- properties = new ArrayList<>();
- TitanOperationStatus findAllRes = propertyOperation.findAllResourcePropertiesRecursively(resourceUid, properties);
- if (findAllRes != TitanOperationStatus.OK) {
- return findAllRes;
- }
- alreadyProcessedResources.put(resourceUid, properties);
- }
- log.debug("After getting properties of resource {}. Number of properties is {}", resourceUid, (properties == null ? 0 : properties.size()));
- if (false == properties.isEmpty()) {
-
- String resourceInstanceUid = resourceInstance.getUniqueId();
-
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> propertyValuesRes = propertyOperation.getAllPropertiesOfResourceInstanceOnlyPropertyDefId(resourceInstanceUid);
- log.debug("After fetching property under resource instance {}", resourceInstanceUid);
- if (propertyValuesRes.isRight()) {
- TitanOperationStatus status = propertyValuesRes.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- return status;
- }
- }
-
- Map<String, ComponentInstanceProperty> propertyIdToValue = new HashMap<>();
- populateMapperWithPropertyValues(propertyValuesRes, propertyIdToValue);
-
- List<ComponentInstanceProperty> resourceInstancePropertyList = new ArrayList<>();
- for (PropertyDefinition propertyDefinition : properties) {
-
- String defaultValue = propertyDefinition.getDefaultValue();
- String value = defaultValue;
- String valueUid = null;
-
- String propertyId = propertyDefinition.getUniqueId();
- ComponentInstanceProperty valuedProperty = propertyIdToValue.get(propertyId);
- if (valuedProperty != null) {
- String newValue = valuedProperty.getValue();
- // if (newValue != null) {
- value = newValue;
- // }
-
- valueUid = valuedProperty.getValueUniqueUid();
- log.trace("Found value {} under resource instance which override the default value {}" , value, defaultValue);
- }
- ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty(propertyDefinition, value, valueUid);
-
- // TODO: currently ignore constraints since they are not
- // inuse and cause to error in convertion to object.
- resourceInstanceProperty.setConstraints(null);
-
- resourceInstancePropertyList.add(resourceInstanceProperty);
-
- }
-
- resourceInstancesProperties.put(resourceInstanceUid, resourceInstancePropertyList);
- }
-
- }
-
- component.setComponentInstancesProperties(resourceInstancesProperties);
- }
-
- return TitanOperationStatus.OK;
- }
-
- private void populateMapperWithPropertyValues(Either<List<ComponentInstanceProperty>, TitanOperationStatus> propertyValuesRes, Map<String, ComponentInstanceProperty> propertyIdToValue) {
-
- if (propertyValuesRes.isLeft()) {
- List<ComponentInstanceProperty> resourceInstanceValues = propertyValuesRes.left().value();
- if (resourceInstanceValues != null) {
- for (ComponentInstanceProperty resourceInstanceProperty : resourceInstanceValues) {
- propertyIdToValue.put(resourceInstanceProperty.getUniqueId(), resourceInstanceProperty);
- }
- }
- }
- }
-
- public abstract Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction);
-
- protected abstract StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type);
-
- protected abstract <T extends Component> StorageOperationStatus updateDerived(Component component, Component currentComponent, ComponentMetadataData updatedResourceData, Class<T> clazz);
-
- public abstract Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete, boolean inTransaction);
-
- protected Either<Component, StorageOperationStatus> internalMarkComponentToDelete(Component componentToDelete, boolean inTransaction) {
- Either<Component, StorageOperationStatus> result = null;
-
- if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
- // component already marked for delete
- result = Either.left(componentToDelete);
- return result;
- } else {
-
- ComponentMetadataData componentMetaData = getMetaDataFromComponent(componentToDelete);
-
- componentMetaData.getMetadataDataDefinition().setIsDeleted(true);
- componentMetaData.getMetadataDataDefinition().setHighestVersion(false);
- componentMetaData.getMetadataDataDefinition().setLastUpdateDate(System.currentTimeMillis());
- try {
- Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentMetaData, ComponentMetadataData.class);
-
- StorageOperationStatus updateComponent;
- if (updateNode.isRight()) {
- log.debug("Failed to update component {}. status is {}", componentMetaData.getUniqueId(), updateNode.right().value());
- updateComponent = DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value());
- result = Either.right(updateComponent);
- return result;
- }
-
- result = Either.left(componentToDelete);
- return result;
- } finally {
-
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("updateResource operation : Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("updateResource operation : Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
-
- }
- }
- }
-
- private Either<List<RequirementDefinition>, TitanOperationStatus> convertReqDataListToReqDefList(ComponentInstance componentInstance, List<ImmutablePair<RequirementData, GraphEdge>> requirementData) {
- ConvertDataToDef<RequirementDefinition, RequirementData> convertor = (instance, data, edge) -> convertReqDataToReqDef(instance, data, edge);
- AddOwnerData<RequirementDefinition> dataAdder = (reqDef, compInstance) -> addOwnerDataReq(reqDef, compInstance);
- return convertDataToDefinition(componentInstance, requirementData, convertor, dataAdder);
- }
-
- private Either<List<CapabilityDefinition>, TitanOperationStatus> convertCapDataListToCapDefList(ComponentInstance componentInstance, List<ImmutablePair<CapabilityData, GraphEdge>> capabilityData) {
- ConvertDataToDef<CapabilityDefinition, CapabilityData> convertor = (instance, data, edge) -> convertCapDataToCapDef(instance, data, edge);
- AddOwnerData<CapabilityDefinition> dataAdder = (capDef, compInstance) -> addOwnerDataCap(capDef, compInstance);
- Either<List<CapabilityDefinition>, TitanOperationStatus> convertationResult = convertDataToDefinition(componentInstance, capabilityData, convertor, dataAdder);
- if (convertationResult.isLeft()) {
- convertationResult = componentInstanceOperation.updateCapDefPropertyValues(componentInstance, convertationResult.left().value());
- }
- return convertationResult;
- }
-
- private Either<CapabilityDefinition, TitanOperationStatus> convertCapDataToCapDef(ComponentInstance componentInstance, CapabilityData data, GraphEdge edge) {
- Either<CapabilityDefinition, TitanOperationStatus> eitherDef = capabilityOperation.getCapabilityByCapabilityData(data);
-
- if (eitherDef.isLeft()) {
- CapabilityDefinition capDef = eitherDef.left().value();
- Map<String, Object> properties = edge.getProperties();
- if (properties != null) {
- String name = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty());
- String source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty());
- List<String> sourcesList = new ArrayList<String>();
- capabilityOperation.getCapabilitySourcesList(source, sourcesList);
- capDef.setName(name);
- capDef.setCapabilitySources(sourcesList);
- capDef.setPath(toscaDefinitionPathCalculator.calculateToscaDefinitionPath(componentInstance, edge));
-
- String requiredOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
- if (requiredOccurrences != null) {
- capDef.setMinOccurrences(requiredOccurrences);
- }
- String leftOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
- if (leftOccurrences != null) {
- capDef.setMaxOccurrences(leftOccurrences);
- }
-
- }
- eitherDef = Either.left(capDef);
- }
- return eitherDef;
- }
-
- private Either<RequirementDefinition, TitanOperationStatus> convertReqDataToReqDef(ComponentInstance componentInstance, RequirementData data, GraphEdge edge) {
- Either<RequirementDefinition, TitanOperationStatus> eitherDef = requirementOperation.getRequirement(data.getUniqueId());
-
- if (eitherDef.isLeft()) {
- RequirementDefinition requirementDef = eitherDef.left().value();
- Map<String, Object> properties = edge.getProperties();
- if (properties != null) {
- String name = (String) properties.get(GraphEdgePropertiesDictionary.NAME.getProperty());
- requirementDef.setName(name);
- String requiredOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty());
- if (requiredOccurrences != null) {
- requirementDef.setMinOccurrences(requiredOccurrences);
- }
- requirementDef.setPath(toscaDefinitionPathCalculator.calculateToscaDefinitionPath(componentInstance, edge));
- String leftOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty());
- if (leftOccurrences != null) {
- requirementDef.setMaxOccurrences(leftOccurrences);
- }
- }
- eitherDef = Either.left(requirementDef);
- }
- return eitherDef;
- }
-
- private <Def, Data> Either<List<Def>, TitanOperationStatus> convertDataToDefinition(ComponentInstance componentInstance, List<ImmutablePair<Data, GraphEdge>> requirementData, ConvertDataToDef<Def, Data> convertor, AddOwnerData<Def> dataAdder) {
- Either<List<Def>, TitanOperationStatus> eitherResult;
- // Convert Data To Definition
- Stream<Either<Def, TitanOperationStatus>> reqDefStream = requirementData.stream().map(e -> convertor.convert(componentInstance, e.left, e.right));
-
- // Collect But Stop After First Error
- List<Either<Def, TitanOperationStatus>> filteredReqDefList = StreamUtils.takeWhilePlusOne(reqDefStream, p -> p.isLeft()).collect(Collectors.toList());
- Optional<Either<Def, TitanOperationStatus>> optionalError = filteredReqDefList.stream().filter(p -> p.isRight()).findAny();
- if (optionalError.isPresent()) {
- eitherResult = Either.right(optionalError.get().right().value());
- } else {
- // Convert From Either To Definition And Collect
- List<Def> reqDefList = filteredReqDefList.stream().map(e -> e.left().value()).collect(Collectors.toList());
- // Add Owner Data
- reqDefList.forEach(e -> dataAdder.addData(e, componentInstance));
- eitherResult = Either.left(reqDefList);
- }
-
- return eitherResult;
- }
-
- interface ConvertDataToDef<Def, Data> {
- Either<Def, TitanOperationStatus> convert(ComponentInstance compInstance, Data d, GraphEdge edge);
- }
-
- interface AddOwnerData<Def> {
- void addData(Def def, ComponentInstance compInstance);
- }
-
- private void addOwnerDataCap(CapabilityDefinition capDef, ComponentInstance componentInstance) {
- capDef.setOwnerId(componentInstance.getUniqueId());
- capDef.setOwnerName(componentInstance.getName());
- }
-
- private void addOwnerDataReq(RequirementDefinition reqDef, ComponentInstance componentInstance) {
- reqDef.setOwnerId(componentInstance.getUniqueId());
- reqDef.setOwnerName(componentInstance.getName());
- }
-
- public Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> getRequirements(Component component, NodeTypeEnum nodeTypeEnum, boolean inTransaction) {
- final HashMap<String, List<RequirementDefinition>> emptyMap = new HashMap<>();
- Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> eitherResult = Either.left(emptyMap);
- try {
- List<ComponentInstance> componentInstances = component.getComponentInstances();
- if (componentInstances != null) {
- Function<ComponentInstance, Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus>> dataCollector = e -> componentInstanceOperation.getRequirements(e, nodeTypeEnum);
- Either<List<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus>>>, TitanOperationStatus> eitherDataCollected = collectDataFromComponentsInstances(componentInstances,
- dataCollector);
- if (eitherDataCollected.isRight()) {
- eitherResult = Either.right(eitherDataCollected.right().value());
- } else {
- // Converts Data to Def stop if encountered conversion error
- DataDefConvertor<RequirementDefinition, RequirementData> someConvertor = (e1, e2) -> convertReqDataListToReqDefList(e1, e2);
- Either<List<List<RequirementDefinition>>, TitanOperationStatus> fullDefList = convertDataToDefComponentLevel(eitherDataCollected.left().value(), someConvertor);
- if (fullDefList.isRight()) {
- eitherResult = Either.right(fullDefList.right().value());
- } else {
- Stream<RequirementDefinition> defStream = fullDefList.left().value().stream().flatMap(e -> e.stream());
- // Collect to Map and using grouping by
- Map<String, List<RequirementDefinition>> capTypeCapListMap = defStream.collect(Collectors.groupingBy(e -> e.getCapability()));
- eitherResult = Either.left(capTypeCapListMap);
- }
-
- }
-
- }
- } finally {
- if (inTransaction == false) {
- titanGenericDao.commit();
- }
- }
-
- return eitherResult;
- }
-
- public Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> getCapabilities(Component component, NodeTypeEnum nodeTypeEnum, boolean inTransaction) {
- final HashMap<String, List<CapabilityDefinition>> emptyMap = new HashMap<>();
- Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> eitherResult = Either.left(emptyMap);
- try {
- List<ComponentInstance> componentInstances = component.getComponentInstances();
- if (componentInstances != null) {
- Function<ComponentInstance, Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus>> dataCollector = e -> componentInstanceOperation.getCapabilities(e, nodeTypeEnum);
- Either<List<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus>>>, TitanOperationStatus> eitherDataCollected = collectDataFromComponentsInstances(componentInstances,
- dataCollector);
- if (eitherDataCollected.isRight()) {
- eitherResult = Either.right(eitherDataCollected.right().value());
- } else {
- // Converts CapData to CapDef removes stop if encountered
- // conversion error
- DataDefConvertor<CapabilityDefinition, CapabilityData> someConvertor = (e1, e2) -> convertCapDataListToCapDefList(e1, e2);
- Either<List<List<CapabilityDefinition>>, TitanOperationStatus> fullDefList = convertDataToDefComponentLevel(eitherDataCollected.left().value(), someConvertor);
- if (fullDefList.isRight()) {
- eitherResult = Either.right(fullDefList.right().value());
- } else {
- Stream<CapabilityDefinition> defStream = fullDefList.left().value().stream().flatMap(e -> e.stream());
- // Collect to Map grouping by Type
- Map<String, List<CapabilityDefinition>> capTypeCapListMap = defStream.collect(Collectors.groupingBy(e -> e.getType()));
- eitherResult = Either.left(capTypeCapListMap);
- }
-
- }
-
- }
- } finally {
- if (inTransaction == false) {
- titanGenericDao.commit();
- }
- }
-
- return eitherResult;
- }
-
- public <Data> Either<List<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>>>, TitanOperationStatus> collectDataFromComponentsInstances(List<ComponentInstance> componentInstances,
- Function<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>> dataGetter) {
- Either<List<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>>>, TitanOperationStatus> eitherResult;
-
- // Get List of Each componentInstance and it's Capabilities Data
- Stream<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>>> ownerDataStream = componentInstances.stream().map(element -> new ImmutablePair<>(element, dataGetter.apply(element)));
- // Collect but stop after first error
- List<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>>> ownerCapDataList = StreamUtils
- .takeWhilePlusOne(ownerDataStream, p -> p.right.isLeft() || p.right.isRight() && p.right.right().value() == TitanOperationStatus.NOT_FOUND).collect(Collectors.toList());
-
- Optional<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>>> optionalError = ownerCapDataList.stream()
- .filter(p -> p.right.isRight() && p.right.right().value() != TitanOperationStatus.NOT_FOUND).findAny();
- if (optionalError.isPresent()) {
- eitherResult = Either.right(optionalError.get().right.right().value());
- } else {
- eitherResult = Either.left(ownerCapDataList.stream().filter(p -> p.right.isLeft()).collect(Collectors.toList()));
- }
-
- return eitherResult;
- }
-
- interface DataDefConvertor<Def, Data> {
- Either<List<Def>, TitanOperationStatus> convertDataToDefComponentInstance(ComponentInstance componentInstance, List<ImmutablePair<Data, GraphEdge>> data);
- }
-
- public <Def, Data> Either<List<List<Def>>, TitanOperationStatus> convertDataToDefComponentLevel(List<ImmutablePair<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>>> ownerCapDataList,
- DataDefConvertor<Def, Data> convertor) {
- // Converts CapData to CapDef removes stop if encountered conversion
- // error
- TitanOperationStatus error = null;
- List<List<Def>> defList = new ArrayList<>();
- for (int i = 0; i < ownerCapDataList.size(); i++) {
- ImmutablePair<ComponentInstance, Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus>> immutablePair = ownerCapDataList.get(i);
- Either<List<Def>, TitanOperationStatus> convertCapDataListToCapDefList = convertor.convertDataToDefComponentInstance(immutablePair.left, immutablePair.right.left().value());
- if (convertCapDataListToCapDefList.isRight()) {
- error = convertCapDataListToCapDefList.right().value();
- break;
- } else {
- defList.add(convertCapDataListToCapDefList.left().value());
- }
-
- }
- Either<List<List<Def>>, TitanOperationStatus> eitherResult = (error != null) ? Either.right(error) : Either.left(defList);
- return eitherResult;
-
- }
-
- private Map<String, ComponentMetadataData> findLatestVersion(List<ComponentMetadataData> resourceDataList) {
- Map<Pair<String, String>, ComponentMetadataData> latestVersionMap = new HashMap<Pair<String, String>, ComponentMetadataData>();
- for (ComponentMetadataData resourceData : resourceDataList) {
- ComponentMetadataData latestVersionData = resourceData;
-
- ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition();
- Pair<String, String> pair = createKeyPair(latestVersionData);
- if (latestVersionMap.containsKey(pair)) {
- latestVersionData = latestVersionMap.get(pair);
- String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion();
- String newVersion = metadataDataDefinition.getVersion();
- if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) {
- latestVersionData = resourceData;
- }
- }
- if (log.isDebugEnabled())
- log.debug("last certified version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion());
-
- latestVersionMap.put(pair, latestVersionData);
- }
-
- Map<String, ComponentMetadataData> resVersionMap = new HashMap<String, ComponentMetadataData>();
- for (ComponentMetadataData resourceData : latestVersionMap.values()) {
- ComponentMetadataData latestVersionData = resourceData;
- ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition();
- if (resVersionMap.containsKey(metadataDataDefinition.getUUID())) {
- latestVersionData = resVersionMap.get(metadataDataDefinition.getUUID());
- String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion();
- String newVersion = metadataDataDefinition.getVersion();
- if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) {
- latestVersionData = resourceData;
- }
- }
- if (log.isDebugEnabled())
- log.debug("last uuid version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion());
- resVersionMap.put(latestVersionData.getMetadataDataDefinition().getUUID(), latestVersionData);
- }
-
- return resVersionMap;
- }
-
- private Pair<String, String> createKeyPair(ComponentMetadataData metadataData) {
- Pair<String, String> pair = null;
- NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel());
- switch (label) {
- case Resource:
- pair = new ImmutablePair<String, String>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name());
- break;
- default:
- pair = new ImmutablePair<String, String>(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel());
- break;
- }
-
- return pair;
- }
-
- public Either<Collection<ComponentMetadataData>, StorageOperationStatus> getLatestVersionNotAbstractComponentsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
- try {
-
- // Map<String, Object> hasPpropertiesToMatch = new HashMap<>();
- // Map<String, Object> hasNotPpropertiesToMatch = new HashMap<>();
- List<ImmutableTriple<QueryType, String, Object>> properties = new ArrayList<>();
- if (componentTypeEnum.equals(ComponentTypeEnum.RESOURCE)) {
- // hasPpropertiesToMatch.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(),
- // isAbstract);
- properties.add(new ImmutableTriple<>(QueryType.HAS, GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), isAbstract));
-
- if (internalComponentType != null) {
- switch (internalComponentType.toLowerCase()) {
- case "vf":
- properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name()));
-// properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name()));
- // hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(),
- // ResourceTypeEnum.VF.name());
- break;
- case "service":
- properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VFC.name()));
- properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VFCMT.name()));
- properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.CVFC.name()));
-// properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name()));
- // hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(),
- // ResourceTypeEnum.VFC.name());
- break;
- case "vl":
- properties.add(new ImmutableTriple<>(QueryType.HAS, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name()));
- // hasPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(),
- // ResourceTypeEnum.VL.name());
- break;
- default:
- break;
- }
- }
- }
- // hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(),
- // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
- properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()));
- // hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.IS_DELETED.getProperty(),
- // true);
- properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.IS_DELETED.getProperty(), true));
- // Either<List<ComponentMetadataData>, TitanOperationStatus>
- // resourceNodes = titanGenericDao.getByCriteria(
- // componentTypeEnum.getNodeType(), hasPpropertiesToMatch,
- // hasNotPpropertiesToMatch,
- // ComponentMetadataData.class);
- Either<List<ComponentMetadataData>, TitanOperationStatus> resourceNodes = titanGenericDao.getByCriteria(componentTypeEnum.getNodeType(), ComponentMetadataData.class, properties);
- if (resourceNodes.isRight()) {
- // in case of NOT_FOUND from Titan client return to UI empty
- // list
- if (resourceNodes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- return Either.left(new ArrayList<>());
- } else {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceNodes.right().value()));
- }
- } else {
- List<ComponentMetadataData> resourceDataList = resourceNodes.left().value();
- Collection<ComponentMetadataData> resCollection = resourceDataList;
- if (isHighest != null && isHighest) {
- Map<String, ComponentMetadataData> latestVersionListMap = findLatestVersion(resourceDataList);
- resCollection = latestVersionListMap.values();
- }
- return Either.left(resCollection);
- }
- } finally {
- titanGenericDao.commit();
- }
-
- }
-
- public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
- try {
- List<Component> result = new ArrayList<>();
- Map<String, ResourceTypeEnum> componentUidsMap = new HashMap<>();
- if (componentUids == null) {
- Either<Collection<ComponentMetadataData>, StorageOperationStatus> resourceNodes = getLatestVersionNotAbstractComponentsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType);
- if (resourceNodes.isRight()) {
- return Either.right(resourceNodes.right().value());
- }
- Collection<ComponentMetadataData> collection = resourceNodes.left().value();
-
- if (collection == null) {
- componentUids = new ArrayList<>();
- } else {
- componentUids = collection.stream().map(p -> p.getMetadataDataDefinition().getUniqueId()).collect(Collectors.toList());
- // collection.forEach(p -> {
- // if (NodeTypeEnum.Resource.getName().equals(p.getLabel()))
- // {
- // componentUidsMap.put(p.getMetadataDataDefinition().getUniqueId(),
- // ((ResourceMetadataDataDefinition)
- // p.getMetadataDataDefinition()).getResourceType());
- // }
- // });
-
- }
-
- }
- if (false == componentUids.isEmpty()) {
-
- Manager manager = new Manager();
- int numberOfWorkers = 5;
-
- manager.init(numberOfWorkers);
- for (String componentUid : componentUids) {
- ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
- // ResourceTypeEnum type =
- // componentUidsMap.get(componentUid);
- // if (type != null && ResourceTypeEnum.VL.equals(type)) {
- if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) {
- componentParametersView.setIgnoreCapabilities(false);
- componentParametersView.setIgnoreRequirements(false);
- }
- manager.addJob(new Job() {
- @Override
- public Either<Component, StorageOperationStatus> doWork() {
- Either<Component, StorageOperationStatus> component = getComponent(componentUid, componentParametersView, false);
- return component;
- }
- });
- }
- LinkedBlockingQueue<Either<Component, StorageOperationStatus>> res = manager.start();
-
- for (Either<Component, StorageOperationStatus> resource : res) {
- if (resource == null) {
- if (log.isDebugEnabled())
- log.debug("Failed to fetch resource returned null ");
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- if (resource.isRight()) {
- if (log.isDebugEnabled())
- log.debug("Failed to fetch resource for error is {}", resource.right().value());
- return Either.right(resource.right().value());
- }
- Component component = resource.left().value();
- component.setContactId(null);
- component.setCreationDate(null);
- component.setCreatorUserId(null);
- component.setCreatorFullName(null);
- component.setLastUpdateDate(null);
- component.setLastUpdaterUserId(null);
- component.setLastUpdaterFullName(null);
- component.setNormalizedName(null);
- result.add(resource.left().value());
- }
-
- if (componentUids.size() != result.size()) {
- if (log.isDebugEnabled())
- log.debug("one of the workers failed to complete job ");
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- }
-
- return Either.left(result);
-
- } finally {
- titanGenericDao.commit();
- }
- }
-
- private ComponentParametersView buildComponentViewForNotAbstract() {
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- // componentParametersView.setIgnoreRequirements(false);
- // componentParametersView.setIgnoreCapabilities(false);
- componentParametersView.setIgnoreCategories(false);
- componentParametersView.setIgnoreAllVersions(false);
- componentParametersView.setIgnoreAllVersions(false);
- return componentParametersView;
- }
-
- protected TitanOperationStatus setCapabilitiesFromGraph(String uniqueId, Component component, NodeTypeEnum nodeType) {
- TitanOperationStatus titanStatus;
- Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> eitherCapabilities = getCapabilities(component, nodeType, true);
- if (eitherCapabilities.isLeft()) {
- titanStatus = TitanOperationStatus.OK;
- Map<String, List<CapabilityDefinition>> capabilities = eitherCapabilities.left().value();
- if (capabilities != null && !capabilities.isEmpty()) {
- component.setCapabilities(capabilities);
- }
- } else {
- titanStatus = eitherCapabilities.right().value();
- }
- return titanStatus;
- }
-
- protected TitanOperationStatus setRequirementsFromGraph(String uniqueId, Component component, NodeTypeEnum nodeType) {
- TitanOperationStatus status;
- Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> eitherRequirements = getRequirements(component, nodeType, false);
- if (eitherRequirements.isLeft()) {
- status = TitanOperationStatus.OK;
- Map<String, List<RequirementDefinition>> requirements = eitherRequirements.left().value();
- if (requirements != null && !requirements.isEmpty()) {
- component.setRequirements(requirements);
- }
- } else {
- status = eitherRequirements.right().value();
- }
- return status;
- }
-
- protected boolean isComponentExist(String componentId, NodeTypeEnum nodeType) {
- boolean result = true;
- Either<TitanVertex, TitanOperationStatus> compVertex = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId);
- if (compVertex.isRight()) {
- log.debug("failed to fetch vertex of component data for id {}", componentId);
- result = false;
-
- }
- return result;
- }
-
- <T> Either<T, StorageOperationStatus> getLightComponent(String id, NodeTypeEnum nodeType, boolean inTransaction) {
-
- T component = null;
- try {
- log.debug("Starting to build light component of type {}, id {}", nodeType, id);
- Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
- if (graphResult.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
- }
- TitanGraph titanGraph = graphResult.left().value();
- Iterable<TitanVertex> vertecies = titanGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), id).vertices();
- if (vertecies != null) {
- Iterator<TitanVertex> iterator = vertecies.iterator();
- if (iterator != null && iterator.hasNext()) {
- Vertex vertex = iterator.next();
- Map<String, Object> resourceProperties = titanGenericDao.getProperties(vertex);
- ComponentMetadataData componentMetadataData = GraphElementFactory.createElement(nodeType.getName(), GraphElementTypeEnum.Node, resourceProperties, ComponentMetadataData.class);
- component = (T) convertComponentMetadataDataToComponent(componentMetadataData);
-
- // get creator
- Iterator<Edge> iterCreator = vertex.edges(Direction.IN, GraphEdgeLabels.CREATOR.name());
- if (iterCreator.hasNext() == false) {
- log.debug("no creator was defined for component {}", id);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- Vertex vertexCreator = iterCreator.next().outVertex();
- UserData creator = GraphElementFactory.createElement(NodeTypeEnum.User.getName(), GraphElementTypeEnum.Node, titanGenericDao.getProperties(vertexCreator), UserData.class);
- log.debug("Build component : set creator userId to {}", creator.getUserId());
- String fullName = buildFullName(creator);
- log.debug("Build component : set creator full name to {}", fullName);
- ((Component) component).setCreatorUserId(creator.getUserId());
- ((Component) component).setCreatorFullName(fullName);
-
- // get modifier
- Iterator<Edge> iterModifier = vertex.edges(Direction.IN, GraphEdgeLabels.LAST_MODIFIER.name());
-
- if (iterModifier.hasNext() == false) {
- log.debug("no modifier was defined for component {}", id);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- Vertex vertexModifier = iterModifier.next().outVertex();
- UserData modifier = GraphElementFactory.createElement(NodeTypeEnum.User.getName(), GraphElementTypeEnum.Node, titanGenericDao.getProperties(vertexModifier), UserData.class);
- log.debug("Build component : set last modifier userId to {}", creator.getUserId());
- fullName = buildFullName(modifier);
- log.debug("Build component : set last modifier full name to {}", fullName);
- ((Component) component).setLastUpdaterUserId(modifier.getUserId());
- ((Component) component).setLastUpdaterFullName(fullName);
-
- // get category
- TitanOperationStatus status = setComponentCategoriesFromGraph((Component) component);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- } else {
- // Nothing found
- log.debug("Component with id {} not found", id);
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- } else {
- // Nothing found
- log.debug("Component with id {} not found", id);
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- log.debug("Ended to build light component of type {}, id {}", nodeType, id);
- return Either.left(component);
- } finally {
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- }
- }
-
- Either<Component, StorageOperationStatus> getMetadataComponent(String id, NodeTypeEnum nodeType, boolean inTransaction) {
- Component component = null;
- try {
- log.debug("Starting to build metadata component of type {}, id {}", nodeType, id);
- Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
- if (graphResult.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
- }
- TitanGraph titanGraph = graphResult.left().value();
- Iterable<TitanVertex> vertecies = titanGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), id).vertices();
- if (vertecies != null) {
- Iterator<TitanVertex> iterator = vertecies.iterator();
- if (iterator != null && iterator.hasNext()) {
- Vertex vertex = iterator.next();
- Map<String, Object> resourceProperties = titanGenericDao.getProperties(vertex);
- ComponentMetadataData componentMetadataData = GraphElementFactory.createElement(nodeType.getName(), GraphElementTypeEnum.Node, resourceProperties, ComponentMetadataData.class);
- component = convertComponentMetadataDataToComponent(componentMetadataData);
- } else {
- // Nothing found
- log.debug("Component with id {} not found", id);
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- } else {
- // Nothing found
- log.debug("Component with id {} not found", id);
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- log.debug("Ended to build metadata component of type {}, id {}", nodeType, id);
- return Either.left(component);
- } finally {
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- }
- }
-
- public Either<Integer, StorageOperationStatus> getComponentInstanceCoutner(String origServiceId, NodeTypeEnum nodeType) {
- Either<Integer, StorageOperationStatus> result;
- Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
- if (graphResult.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
- return result;
- }
- Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), origServiceId);
- if (vertexService.isRight()) {
- log.debug("failed to fetch vertex of component metadata, nodeType:{} , id: {}", nodeType, origServiceId);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value()));
- return result;
- }
- Vertex vertex = vertexService.left().value();
- Integer instanceCounter = vertex.value(GraphPropertiesDictionary.INSTANCE_COUNTER.getProperty());
- return Either.left(instanceCounter);
- }
-
- protected TitanOperationStatus setComponentInstancesPropertiesFromGraph(Component component) {
-
- List<ComponentInstance> resourceInstances = component.getComponentInstances();
-
- Map<String, List<ComponentInstanceProperty>> resourceInstancesProperties = new HashMap<>();
-
- Map<String, List<PropertyDefinition>> alreadyProcessedResources = new HashMap<>();
-
- Map<String, List<ComponentInstanceProperty>> alreadyProcessedInstances = new HashMap<>();
-
- Map<String, ImmutablePair<ComponentInstance, Integer>> processedInstances = new HashMap<>();
-
- if (resourceInstances != null) {
-
- for (ComponentInstance resourceInstance : resourceInstances) {
-
- List<String> path = new ArrayList<>();
- path.add(resourceInstance.getUniqueId());
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> componentInstanceProperties = componentInstanceOperation.getComponentInstanceProperties(resourceInstance, alreadyProcessedResources, alreadyProcessedInstances,
- processedInstances, path);
-
- if (componentInstanceProperties.isRight()) {
- TitanOperationStatus status = componentInstanceProperties.right().value();
- if (status != TitanOperationStatus.OK) {
- return status;
- }
- }
-
- List<ComponentInstanceProperty> listOfProps = componentInstanceProperties.left().value();
- String resourceInstanceUid = resourceInstance.getUniqueId();
- resourceInstancesProperties.put(resourceInstanceUid, listOfProps);
-
- // alreadyProcessedInstances.put(resourceInstance.getUniqueId(),
- // resourceInstance);
-
- processedInstances.put(resourceInstance.getUniqueId(), new ImmutablePair<ComponentInstance, Integer>(resourceInstance, path.size()));
- path.remove(path.size() - 1);
-
- }
-
- }
-
- Either<Map<String, Map<String, ComponentInstanceProperty>>, TitanOperationStatus> findAllPropertiesValuesOnInstances = componentInstanceOperation.findAllPropertyValueOnInstances(processedInstances);
- // 1. check status
- if (findAllPropertiesValuesOnInstances.isRight()) {
- TitanOperationStatus status = findAllPropertiesValuesOnInstances.right().value();
- if (status != TitanOperationStatus.OK) {
- return status;
- }
- }
- // 2. merge data from rules on properties (resourceInstancesProperties)
- propertyOperation.updatePropertiesByPropertyValues(resourceInstancesProperties, findAllPropertiesValuesOnInstances.left().value());
-
- component.setComponentInstancesProperties(resourceInstancesProperties);
-
- return TitanOperationStatus.OK;
- }
-
- protected TitanOperationStatus setComponentInstancesInputsFromGraph(String uniqueId, Component component) {
-
- Map<String, List<ComponentInstanceInput>> resourceInstancesInputs = new HashMap<>();
- TitanOperationStatus status = TitanOperationStatus.OK;
- List<ComponentInstance> componentInstances = component.getComponentInstances();
- if (componentInstances != null) {
- for (ComponentInstance resourceInstance : componentInstances) {
- Either<List<ComponentInstanceInput>, TitanOperationStatus> eitherRIAttributes = inputOperation.getAllInputsOfResourceInstance(resourceInstance);
- if (eitherRIAttributes.isRight()) {
- if (eitherRIAttributes.right().value() != TitanOperationStatus.NOT_FOUND) {
- status = eitherRIAttributes.right().value();
- break;
- }
- } else {
- resourceInstancesInputs.put(resourceInstance.getUniqueId(), eitherRIAttributes.left().value());
- }
- }
- if (!resourceInstancesInputs.isEmpty())
- component.setComponentInstancesInputs(resourceInstancesInputs);
- }
-
- return status;
- }
-
- public Either<String, StorageOperationStatus> getInvariantUUID(NodeTypeEnum nodeType, String componentId, boolean inTransaction) {
- Either<String, StorageOperationStatus> res = null;
- try {
- Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId);
- if (vertexByProperty.isRight()) {
- TitanOperationStatus status = vertexByProperty.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- res = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- } else {
- Vertex v = vertexByProperty.left().value();
- String invariantUUID = v.value(GraphPropertiesDictionary.INVARIANT_UUID.getProperty());
-
- if (invariantUUID == null || invariantUUID.isEmpty()) {
-
- log.info("The component {} has empty invariant UUID.", componentId);
- res = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.INVALID_ELEMENT));
-
- }
- res = Either.left(invariantUUID);
- }
- } finally {
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- }
- return res;
- }
-
- protected TitanOperationStatus setGroupsFromGraph(String uniqueId, Component component, NodeTypeEnum nodeTypeEnum) {
-
- Either<List<GroupDefinition>, TitanOperationStatus> res = groupOperation.getAllGroupsFromGraph(uniqueId, nodeTypeEnum);
- if (res.isRight()) {
- TitanOperationStatus status = res.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- return TitanOperationStatus.OK;
- } else {
- return status;
- }
- }
- component.setGroups(res.left().value());
-
- return TitanOperationStatus.OK;
-
- }
-
- protected TitanOperationStatus setComponentInputsFromGraph(String uniqueId, Component component, boolean inTransaction) {
-
- List<InputDefinition> inputs = new ArrayList<>();
- TitanOperationStatus status = inputsOperation.findAllResourceInputs(uniqueId, inputs);
- if (status == TitanOperationStatus.OK) {
- component.setInputs(inputs);
- }
-
- return status;
-
- }
-
- protected StorageOperationStatus deleteGroups(NodeTypeEnum nodeType, String componentId) {
-
- Either<List<GroupDefinition>, StorageOperationStatus> deleteRes = groupOperation.deleteAllGroups(componentId, nodeType, true);
-
- if (deleteRes.isRight()) {
- StorageOperationStatus status = deleteRes.right().value();
- return status;
- }
-
- return StorageOperationStatus.OK;
-
- }
-
- protected StorageOperationStatus removeInputsFromComponent(NodeTypeEnum typeEnum, Component component) {
- Either<Map<String, InputDefinition>, StorageOperationStatus> deleteAllInputsAssociatedToNode = inputsOperation.deleteAllInputsAssociatedToNode(typeEnum, component.getUniqueId());
- return deleteAllInputsAssociatedToNode.isRight() ? deleteAllInputsAssociatedToNode.right().value() : StorageOperationStatus.OK;
- }
-
- protected TitanOperationStatus associateInputsToComponent(NodeTypeEnum nodeType, ComponentMetadataData resourceData, List<InputDefinition> properties) {
-
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- log.debug("Cannot find any data type. Status is {}.", status);
- return status;
- }
-
- Map<String, InputDefinition> convertedProperties = new HashMap<>();
-
- if (properties != null) {
- for (InputDefinition propertyDefinition : properties) {
- convertedProperties.put(propertyDefinition.getName(), propertyDefinition);
- }
-
- Either<List<InputDefinition>, TitanOperationStatus> operationStatus = inputsOperation.addInputsToGraph(resourceData.getMetadataDataDefinition().getUniqueId(), nodeType, convertedProperties, allDataTypes.left().value());
- if (operationStatus.isLeft())
- return TitanOperationStatus.OK;
- else
- return operationStatus.right().value();
- }
-
- return TitanOperationStatus.OK;
-
- }
-
- protected TitanOperationStatus associateInputsToComponent(TitanVertex metadataVertex, String componentId, List<InputDefinition> properties) {
-
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- log.debug("Cannot find any data type. Status is {}.", status);
- return status;
- }
-
- Map<String, InputDefinition> convertedProperties = new HashMap<>();
-
- if (properties != null) {
- for (InputDefinition propertyDefinition : properties) {
- convertedProperties.put(propertyDefinition.getName(), propertyDefinition);
- }
-
- return inputsOperation.addInputsToGraph(metadataVertex, componentId, convertedProperties, allDataTypes.left().value());
- }
-
- return TitanOperationStatus.OK;
-
- }
-
- public Either<List<ComponentInstance>, StorageOperationStatus> getAllComponentInstncesMetadata(String componentId, NodeTypeEnum nodeType) {
- Instant start = Instant.now();
- Either<List<ComponentInstance>, StorageOperationStatus> resourceInstancesOfService = componentInstanceOperation.getAllComponentInstancesMetadataOnly(componentId, nodeType);
- Instant end = Instant.now();
- log.debug("TOTAL TIME BL GET INSTANCES: {}", Duration.between(start, end));
- return resourceInstancesOfService;
- }
-
- @Deprecated
- public Either<List<Component>, ActionStatus> getComponentsFromCacheForCatalog(Set<String> components, ComponentTypeEnum componentType) {
-
- Either<ImmutableTriple<List<Component>, List<Component>, Set<String>>, ActionStatus> componentsForCatalog = componentCache.getComponentsForCatalog(components, componentType);
- if (componentsForCatalog.isLeft()) {
- ImmutableTriple<List<Component>, List<Component>, Set<String>> immutableTriple = componentsForCatalog.left().value();
- List<Component> foundComponents = immutableTriple.getLeft();
-
- if (foundComponents != null) {
- // foundComponents.forEach(p -> result.add((Resource)p));
- log.debug("The number of {}s added to catalog from cache is {}", componentType.name().toLowerCase(), foundComponents.size());
-
- }
- List<Component> foundDirtyComponents = immutableTriple.getMiddle();
- Set<String> nonCachedComponents = immutableTriple.getRight();
- int numberDirtyResources = foundDirtyComponents == null ? 0 : foundDirtyComponents.size();
- int numberNonCached = nonCachedComponents == null ? 0 : nonCachedComponents.size();
- log.debug("The number of left {}s for catalog is {}", componentType.name().toLowerCase(), numberDirtyResources + numberNonCached);
- return Either.left(foundComponents);
- }
-
- return Either.right(componentsForCatalog.right().value());
- }
-
- public <T extends ComponentMetadataData> Either<List<T>, TitanOperationStatus> getListOfHighestComponents(NodeTypeEnum nodeTypeEnum, Class<T> clazz) {
-
- long startFetchAllStates = System.currentTimeMillis();
- Map<String, Object> propertiesToMatchHigest = new HashMap<>();
- propertiesToMatchHigest.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
- Either<List<T>, TitanOperationStatus> allHighestStates = titanGenericDao.getByCriteria(nodeTypeEnum, propertiesToMatchHigest, clazz);
- if (allHighestStates.isRight() && allHighestStates.right().value() != TitanOperationStatus.NOT_FOUND) {
- return Either.right(allHighestStates.right().value());
- }
- long endFetchAllStates = System.currentTimeMillis();
-
- if (allHighestStates.isRight()) {
- return Either.left(new ArrayList<>());
- }
- List<T> services = allHighestStates.left().value();
-
- List<T> certifiedHighest = new ArrayList<>();
- List<T> notCertifiedHighest = new ArrayList<>();
- for (T reData : services) {
- if (reData.getMetadataDataDefinition().getState().equals(LifecycleStateEnum.CERTIFIED.name())) {
- certifiedHighest.add(reData);
- } else {
- notCertifiedHighest.add(reData);
- }
- }
-
- log.debug("Fetch catalog {}s all states: certified {}, noncertified {}", nodeTypeEnum.getName(), certifiedHighest.size(), notCertifiedHighest.size());
- log.debug("Fetch catalog {}s all states from graph took {} ms", nodeTypeEnum.getName(), endFetchAllStates - startFetchAllStates);
-
- HashMap<String, String> serviceNames = new HashMap<>();
- for (T data : notCertifiedHighest) {
- String serviceName = data.getMetadataDataDefinition().getName();
- serviceNames.put(serviceName, serviceName);
- }
-
- for (T data : certifiedHighest) {
- String serviceName = data.getMetadataDataDefinition().getName();
- if (!serviceNames.containsKey(serviceName)) {
- notCertifiedHighest.add(data);
- }
- }
-
- return Either.left(notCertifiedHighest);
- }
-
- protected <T extends Component> Either<T, ActionStatus> getComponentFromCacheIfUpToDate(String uniqueId, ComponentMetadataData componentMetadataData, ComponentParametersView componentParametersView, Class<T> clazz,
- ComponentTypeEnum componentTypeEnum) {
-
- long start = System.currentTimeMillis();
- try {
-
- long lastModificationTime = componentMetadataData.getMetadataDataDefinition().getLastUpdateDate();
- Either<Component, ActionStatus> cacheComponentRes = this.componentCache.getComponent(uniqueId, lastModificationTime);
- if (cacheComponentRes.isLeft()) {
- Component cachedComponent = cacheComponentRes.left().value();
-
- // Must calculate allVersions
- if (false == componentParametersView.isIgnoreAllVersions()) {
- Class<? extends ComponentMetadataData> clazz1 = null;
- switch (componentTypeEnum) {
- case RESOURCE:
- clazz1 = ResourceMetadataData.class;
- break;
- case SERVICE:
- clazz1 = ServiceMetadataData.class;
- break;
- case PRODUCT:
- clazz1 = ProductMetadataData.class;
- break;
- default:
- break;
- }
- if (clazz1 != null) {
- Either<Map<String, String>, TitanOperationStatus> versionList = getVersionList(componentTypeEnum.getNodeType(), cachedComponent.getVersion(), cachedComponent.getUUID(), cachedComponent.getSystemName(), clazz1);
- if (versionList.isRight()) {
- return Either.right(ActionStatus.GENERAL_ERROR);
- }
-
- Map<String, String> allVersions = versionList.left().value();
- cachedComponent.setAllVersions(allVersions);
- } else {
- return Either.right(ActionStatus.GENERAL_ERROR);
- }
- }
- if (componentParametersView != null) {
- cachedComponent = componentParametersView.filter(cachedComponent, componentTypeEnum);
- }
- return Either.left(clazz.cast(cachedComponent));
- }
-
- return Either.right(cacheComponentRes.right().value());
-
- } finally {
- log.trace("Fetch component {} with uid {} from cache took {} ms", componentTypeEnum.name().toLowerCase(), uniqueId, System.currentTimeMillis() - start);
- }
- }
-
- public Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> getComponentsFromCacheForCatalog(Map<String, Long> components, ComponentTypeEnum componentType) {
-
- Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> componentsForCatalog = componentCache.getComponentsForCatalog(components, componentType);
- if (componentsForCatalog.isLeft()) {
- ImmutablePair<List<Component>, Set<String>> immutablePair = componentsForCatalog.left().value();
- List<Component> foundComponents = immutablePair.getLeft();
-
- if (foundComponents != null) {
- // foundComponents.forEach(p -> result.add((Resource)p));
- log.debug("The number of {}s added to catalog from cache is {}", componentType.name().toLowerCase(), foundComponents.size());
- }
- Set<String> leftComponents = immutablePair.getRight();
- int numberNonCached = leftComponents == null ? 0 : leftComponents.size();
- log.debug("The number of left {}s for catalog is {}", componentType.name().toLowerCase(), numberNonCached);
-
- ImmutablePair<List<Component>, Set<String>> result = new ImmutablePair<List<Component>, Set<String>>(foundComponents, leftComponents);
- return Either.left(result);
- }
-
- return Either.right(componentsForCatalog.right().value());
- }
-
- /**
- *
- * @param component
- * @param inTransaction
- * @param titanGenericDao
- * @param clazz
- * @return
- */
- public <T> Either<T, StorageOperationStatus> updateComponentFilterResult(Component component, boolean inTransaction, TitanGenericDao titanGenericDao, Class<T> clazz, NodeTypeEnum type, ComponentParametersView filterResult) {
- Either<T, StorageOperationStatus> result = null;
-
- try {
-
- log.debug("In updateComponent. received component uid = {}", (component == null ? null : component.getUniqueId()));
- if (component == null) {
- log.error("Service object is null");
- result = Either.right(StorageOperationStatus.BAD_REQUEST);
- return result;
- }
-
- ComponentMetadataData componentData = getMetaDataFromComponent(component);
-
- log.debug("After converting component to componentData. ComponentData = {}", componentData);
-
- if (componentData.getUniqueId() == null) {
- log.error("Resource id is missing in the request.");
- return Either.right(StorageOperationStatus.BAD_REQUEST);
- }
-
- Either<Integer, StorageOperationStatus> counterStatus = this.getComponentInstanceCoutner(component.getUniqueId(), component.getComponentType().getNodeType());
-
- if (counterStatus.isRight()) {
-
- log.error("Cannot find componentInstanceCounter for component {} in the graph. status is {}", componentData.getUniqueId(), counterStatus);
- // result = sendError(status,
- // StorageOperationStatus.USER_NOT_FOUND);
- return result;
- }
-
- componentData.setComponentInstanceCounter(counterStatus.left().value());
-
- String modifierUserId = component.getLastUpdaterUserId();
- if (modifierUserId == null || modifierUserId.isEmpty()) {
- log.error("UserId is missing in the request.");
- result = Either.right(StorageOperationStatus.BAD_REQUEST);
- return result;
- }
- Either<UserData, TitanOperationStatus> findUser = findUser(modifierUserId);
-
- if (findUser.isRight()) {
- TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user {} in the graph. status is {}", modifierUserId, status);
- // result = sendError(status,
- // StorageOperationStatus.USER_NOT_FOUND);
- return result;
- }
-
- UserData modifierUserData = findUser.left().value();
- String resourceId = component.getUniqueId();
-
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreUsers(false);
- componentParametersView.setIgnoreCategories(false);
- componentParametersView.setIgnoreDerivedFrom(false);
- componentParametersView.setIgnoreArtifacts(false);
- Either<T, StorageOperationStatus> currentComponentResult = this.getComponent(resourceId, componentParametersView, inTransaction);
- if (currentComponentResult.isRight()) {
- log.error("Cannot find resource with id {} in the graph.", resourceId);
- result = Either.right(currentComponentResult.right().value());
- return result;
- }
-
- Component currentComponent = (Component) currentComponentResult.left().value();
- String currentModifier = currentComponent.getLastUpdaterUserId();
-
- if (currentModifier.equals(modifierUserData.getUniqueId())) {
- log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier.");
- } else {
- log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId);
- StorageOperationStatus status = moveLastModifierEdge(component, componentData, modifierUserData, type);
- log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status);
- if (status != StorageOperationStatus.OK) {
- result = Either.right(status);
- return result;
- }
- }
- final long currentTimeMillis = System.currentTimeMillis();
- log.debug("Going to update the last Update Date of the resource from {} to {}", component.getLastUpdateDate(), currentTimeMillis);
- component.setLastUpdateDate(currentTimeMillis);
-
- StorageOperationStatus checkCategories = validateCategories(currentComponent, component, componentData, type);
- if (checkCategories != StorageOperationStatus.OK) {
- result = Either.right(checkCategories);
- return result;
- }
-
- List<String> tags = component.getTags();
- if (tags != null && false == tags.isEmpty()) {
- Either<List<TagData>, StorageOperationStatus> tagsResult = createNewTagsList(tags);
- if (tagsResult.isRight()) {
- result = Either.right(tagsResult.right().value());
- return result;
- }
- List<TagData> tagsToCreate = tagsResult.left().value();
- if (tagsToCreate != null && !tagsToCreate.isEmpty()) {
- tagsToCreate = ImmutableSet.copyOf(tagsToCreate).asList();
- for (TagData tagData : tagsToCreate) {
- log.debug("Before creating tag {}", tagData);
- Either<TagData, TitanOperationStatus> createTagResult = titanGenericDao.createNode(tagData, TagData.class);
- if (createTagResult.isRight()) {
- TitanOperationStatus status = createTagResult.right().value();
- log.error("Cannot find tag {} in the graph. status is {}", tagData, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- log.debug("After creating tag {}", tagData);
- }
- }
- }
-
- Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class);
-
- if (updateNode.isRight()) {
- log.error("Failed to update resource {}. status is {}", component.getUniqueId(), updateNode.right().value());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
- return result;
- }
-
- ComponentMetadataData updatedResourceData = updateNode.left().value();
- log.debug("ComponentData After update is {}", updatedResourceData);
-
- // DE230195 in case resource name changed update TOSCA artifacts
- // file names accordingly
- String newSystemName = updatedResourceData.getMetadataDataDefinition().getSystemName();
- String prevSystemName = currentComponent.getSystemName();
- if (newSystemName != null && !newSystemName.equals(prevSystemName)) {
- Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
- if (toscaArtifacts != null) {
- for (Entry<String, ArtifactDefinition> artifact : toscaArtifacts.entrySet()) {
- Either<ArtifactData, StorageOperationStatus> updateName = generateAndUpdateToscaFileName(component.getComponentType().getValue().toLowerCase(), newSystemName, updatedResourceData.getMetadataDataDefinition().getUniqueId(),
- type, artifact.getValue());
- if (updateName.isRight()) {
- result = Either.right(updateName.right().value());
- return result;
- }
- }
- }
- //TODO call to new Artifact operation in order to update list of artifacts
-
- //US833308 VLI in service - specific network_role property value logic
- if (ComponentTypeEnum.SERVICE == component.getComponentType()) {
- //update method logs success/error and returns boolean (true if nothing fails)
- updateServiceNameInVLIsNetworkRolePropertyValues(component, prevSystemName, newSystemName);
- }
- }
-
-
- if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE)) {
- updateDerived(component, currentComponent, componentData, component.getClass());
- }
-
- Either<T, StorageOperationStatus> updatedResource = getComponent(component.getUniqueId(), filterResult, inTransaction);
- if (updatedResource.isRight()) {
- log.error("Resource id is missing in the request. status is {}", updatedResource.right().value());
- result = Either.right(StorageOperationStatus.BAD_REQUEST);
- return result;
- }
-
- T updatedResourceValue = updatedResource.left().value();
- result = Either.left(updatedResourceValue);
-
- return result;
- } finally {
-
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("updateComponent operation : Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("updateComponent operation : Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- private boolean updateServiceNameInVLIsNetworkRolePropertyValues (Component component, String prevSystemName, String newSystemName) {
- // find VLIs in service
- boolean res = true;
- if(null == component.getComponentInstances() || component.getComponentInstances().isEmpty()){
- return res;
- }
-
- List <ComponentInstance> vlInstances =
- component.getComponentInstances().stream()
- .filter(p -> OriginTypeEnum.VL == p.getOriginType())
- .collect(Collectors.toList());
- if (!vlInstances.isEmpty()) {
- for (ComponentInstance vlInstance : vlInstances){
- // find network_role property
- Optional <ComponentInstanceProperty> networkRoleProperty = component.getComponentInstancesProperties().get(vlInstance.getUniqueId()).stream()
- .filter(p -> PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(p.getName()))
- .findAny();
- res = res && updateNetworkRolePropertyValue(prevSystemName, newSystemName, vlInstance, networkRoleProperty);
- }
- }
- return res;
- }
-
- private boolean updateNetworkRolePropertyValue(String prevSystemName, String newSystemName, ComponentInstance vlInstance, Optional<ComponentInstanceProperty> networkRoleProperty) {
- if (networkRoleProperty.isPresent() && !StringUtils.isEmpty(networkRoleProperty.get().getValue()) ) {
- ComponentInstanceProperty property = networkRoleProperty.get();
- String updatedValue = property.getValue().replaceFirst(prevSystemName, newSystemName);
- property.setValue(updatedValue);
- StorageOperationStatus updateCustomizationUUID;
- //disregard property value rule
- property.setRules(null);
- Either<ComponentInstanceProperty, StorageOperationStatus> result = componentInstanceOperation.updatePropertyValueInResourceInstance(property, vlInstance.getUniqueId(), true);
- if (result.isLeft()) {
- log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
- updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(vlInstance.getUniqueId());
- } else {
- updateCustomizationUUID = StorageOperationStatus.EXEUCTION_FAILED;
- log.debug("Failed to update property value: {} in resource instance {}", updatedValue, vlInstance.getUniqueId());
- }
- return result.isLeft() && StorageOperationStatus.OK == updateCustomizationUUID;
- }
- return true;
- }
-
- public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateAndLastModifierOnGraph( Component component, User modifier, NodeTypeEnum componentType, boolean inTransaction) {
-
- log.debug("Going to update last update date and last modifier info of component {}. ", component.getName());
- Either<ComponentMetadataData, StorageOperationStatus> result = null;
- try{
- String modifierUserId = modifier.getUserId();
- ComponentMetadataData componentData = getMetaDataFromComponent(component);
- String currentUser = component.getLastUpdaterUserId();
- UserData modifierUserData = new UserData();
- modifierUserData.setUserId(modifierUserId);
- if (currentUser.equals(modifierUserId)) {
- log.debug("Graph last modifier edge should not be changed since the modifier is the same as the last modifier.");
- } else {
- log.debug("Going to update the last modifier user of the component from {} to {}", currentUser, modifierUserId);
- StorageOperationStatus status = moveLastModifierEdge(component, componentData, modifierUserData, componentType);
- log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentUser, modifierUserId, status);
- if (status != StorageOperationStatus.OK) {
- result = Either.right(status);
- }
- }
- Either<ComponentMetadataData, TitanOperationStatus> updateNode = null;
- if(result == null){
- log.debug("Going to update the component {} with new last update date. ", component.getName());
- componentData.getMetadataDataDefinition().setLastUpdateDate(System.currentTimeMillis());
- updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class);
- if (updateNode.isRight()) {
- log.error("Failed to update component {}. status is {}", component.getUniqueId(), updateNode.right().value());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
- }
- }
- if(result == null){
- result = Either.left(updateNode.left().value());
- }
- }catch(Exception e){
- log.error("Exception occured during update last update date and last modifier info of component {}. The message is {}. ", component.getName(), e.getMessage());
- }finally {
- if(!inTransaction){
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- return result;
- }
- /**
- * updates component lastUpdateDate on graph node
- * @param component
- * @param componentType
- * @param lastUpdateDate
- * @param inTransaction
- * @return
- */
- public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph( Component component, NodeTypeEnum componentType, Long lastUpdateDate, boolean inTransaction) {
-
- log.debug("Going to update last update date of component {}. ", component.getName());
- Either<ComponentMetadataData, StorageOperationStatus> result = null;
- try{
- ComponentMetadataData componentData = getMetaDataFromComponent(component);
- Either<ComponentMetadataData, TitanOperationStatus> updateNode = null;
- if(result == null){
- log.debug("Going to update the component {} with new last update date. ", component.getName());
- componentData.getMetadataDataDefinition().setLastUpdateDate(lastUpdateDate);
- updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class);
- if (updateNode.isRight()) {
- log.error("Failed to update component {}. status is {}", component.getUniqueId(), updateNode.right().value());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
- }
- }
- if(result == null){
- result = Either.left(updateNode.left().value());
- }
- }catch(Exception e){
- log.error("Exception occured during update last update date of component {}. The message is {}. ", component.getName(), e.getMessage());
- }finally {
- if(!inTransaction){
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- return result;
- }
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java
index 89f8f71e2a..a47f7cfdef 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java
@@ -40,7 +40,7 @@ import fj.data.Either;
@Component("graph-lock-operation")
public class GraphLockOperation implements IGraphLockOperation {
- private static Logger log = LoggerFactory.getLogger(ResourceOperation.class.getName());
+ private static Logger log = LoggerFactory.getLogger(GraphLockOperation.class.getName());
@javax.annotation.Resource
private TitanGenericDao titanGenericDao;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java
index d282ecfae9..4ffea48dee 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java
@@ -20,18 +20,11 @@
package org.openecomp.sdc.be.model.operations.impl;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanVertex;
+import fj.data.Either;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
-import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
@@ -39,64 +32,51 @@ import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
-import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.dao.utils.Constants;
import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-
-import org.openecomp.sdc.be.model.ComponentInstance;
-
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.model.GroupInstanceProperty;
import org.openecomp.sdc.be.model.GroupProperty;
-import org.openecomp.sdc.be.model.GroupTypeDefinition;
import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.resources.data.ArtifactData;
-import org.openecomp.sdc.be.resources.data.AttributeValueData;
-import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
-import org.openecomp.sdc.be.resources.data.GroupData;
import org.openecomp.sdc.be.resources.data.GroupInstanceData;
import org.openecomp.sdc.be.resources.data.PropertyData;
import org.openecomp.sdc.be.resources.data.PropertyValueData;
import org.openecomp.sdc.be.resources.data.UniqueIdData;
import org.openecomp.sdc.common.datastructure.Wrapper;
import org.openecomp.sdc.common.util.ValidationUtils;
-import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("group-instance-operation")
public class GroupInstanceOperation extends AbstractOperation implements IGroupInstanceOperation {
- private static String ADDING_GROUP = "AddingGroupInstance";
-
private static Logger log = LoggerFactory.getLogger(GroupInstanceOperation.class.getName());
@Autowired
@@ -110,72 +90,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
@javax.annotation.Resource
private ApplicationDataTypeCache dataTypeCache;
- @Override
- public Either<GroupInstance, StorageOperationStatus> createGroupInstance(String componentInstId, GroupInstance groupInstance, boolean isCreateLogicalName) {
- Either<GroupInstance, StorageOperationStatus> result = null;
-
- if (!ValidationUtils.validateStringNotEmpty(groupInstance.getCustomizationUUID())) {
- generateCustomizationUUID(groupInstance);
- }
-
- Either<GroupInstance, TitanOperationStatus> addRes = addGroupInstanceToComponentInstance(componentInstId, isCreateLogicalName, groupInstance);
- if (addRes.isRight()) {
- TitanOperationStatus status = addRes.right().value();
- log.error("Failed to add resource instance {} to service {}. status is {}", groupInstance, componentInstId, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- GroupInstance value = addRes.left().value();
- result = Either.left(value);
-
- return result;
-
- }
-
- @Override
- public Either<GroupInstance, StorageOperationStatus> createGroupInstance(TitanVertex ciVertex, String componentInstId, GroupInstance groupInstance, boolean isCreateLogicalName) {
- Either<GroupInstance, StorageOperationStatus> result = null;
-
- if (!ValidationUtils.validateStringNotEmpty(groupInstance.getCustomizationUUID())) {
- generateCustomizationUUID(groupInstance);
- }
-
- Either<TitanVertex, TitanOperationStatus> addComponentInstanceToContainerComponent = addGroupInstanceToContainerComponent(ciVertex, componentInstId, isCreateLogicalName, groupInstance);
-
- if (addComponentInstanceToContainerComponent.isRight()) {
- TitanOperationStatus status = addComponentInstanceToContainerComponent.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- TitanVertex giVertex = addComponentInstanceToContainerComponent.left().value();
- Map<String, Object> properties = titanGenericDao.getProperties(giVertex);
- GroupInstanceData createdGroupInstanceData = GraphElementFactory.createElement(NodeTypeEnum.GroupInstance.getName(), GraphElementTypeEnum.Node, properties, GroupInstanceData.class);
-
- GroupInstance createdGroupInstance = new GroupInstance(createdGroupInstanceData.getGroupDataDefinition());
- createdGroupInstance.setGroupName(groupInstance.getGroupName());
-
- createdGroupInstance.setArtifacts(groupInstance.getArtifacts());
-
- result = Either.left(createdGroupInstance);
-
- return result;
-
- }
-
- @Override
- public Either<GroupInstance, StorageOperationStatus> deleteGroupInstanceInstance(NodeTypeEnum containerNodeType, String containerComponentId, String groupInstUid) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<GroupInstance, StorageOperationStatus> updateGroupInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance) {
- // TODO Auto-generated method stub
- return null;
- }
@Override
public Either<List<GroupInstance>, StorageOperationStatus> getAllGroupInstances(String parentId, NodeTypeEnum parentType) {
@@ -275,55 +189,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
}
@Override
- public Either<GroupInstance, TitanOperationStatus> getGroupInstanceById(String groupResourceId) {
- // TODO Auto-generated method stub
- return getGroupInstanceFromGraph(groupResourceId, false, false);
- }
-
- @Override
- public TitanOperationStatus deleteAllGroupInstances(String componentInstId) {
-
- return deleteAssociatedGroupInstances(componentInstId);
- }
-
- private TitanOperationStatus deleteAssociatedGroupInstances(String resourceInstanceUid) {
- final GraphEdgeLabels edgeConectingToRI = GraphEdgeLabels.GROUP_INST;
- final NodeTypeEnum elementTypeToDelete = NodeTypeEnum.GroupInstance;
- return deleteAssociatedRIElements(elementTypeToDelete, edgeConectingToRI, resourceInstanceUid, () -> GroupInstanceData.class);
- }
-
- private <T extends GraphNode> TitanOperationStatus deleteAssociatedRIElements(NodeTypeEnum elementTypeToDelete, GraphEdgeLabels edgeConectingToRI, String resourceInstanceUid, Supplier<Class<T>> classGen) {
-
- Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> elementsNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid, edgeConectingToRI, elementTypeToDelete,
- classGen.get());
-
- if (elementsNodesRes.isRight()) {
- TitanOperationStatus status = elementsNodesRes.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements", "Failed to find the elements of resource instance " + resourceInstanceUid + ". status is " + status, ErrorSeverity.ERROR);
- return status;
- }
- } else {
-
- List<ImmutablePair<T, GraphEdge>> relationshipNodes = elementsNodesRes.left().value();
- if (relationshipNodes != null) {
- for (ImmutablePair<T, GraphEdge> immutablePair : relationshipNodes) {
- T elementValueDataData = immutablePair.getKey();
- Either<T, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(elementValueDataData, classGen.get());
- if (deleteNode.isRight()) {
- TitanOperationStatus status = deleteNode.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements", "Failed to delete element value node " + elementValueDataData + ". status is " + status, ErrorSeverity.ERROR);
- return status;
- }
- }
- }
-
- }
-
- return TitanOperationStatus.OK;
- }
-
- @Override
public Either<Integer, StorageOperationStatus> increaseAndGetGroupInstancePropertyCounter(String groupInstanceId) {
Either<Integer, StorageOperationStatus> result = null;
@@ -361,18 +226,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
}
@Override
- public Either<Boolean, StorageOperationStatus> isGroupInstanceNameExist(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<ComponentInstance, StorageOperationStatus> getFullGroupInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty groupInstanceProperty, String groupInstanceId, Integer index, boolean inTransaction) {
/// #RULES SUPPORT
/// Ignore rules received from client till support
@@ -425,38 +278,12 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
}
@Override
- public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isvalidate, Integer index, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInGroupInstance(ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction) {
// TODO Auto-generated method stub
// change Propety class
return null;
}
- @Override
- public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public StorageOperationStatus updateCustomizationUUID(String groupInstanceId) {
- Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), groupInstanceId);
- if (vertexByProperty.isRight()) {
- log.debug("Failed to fetch component instance by id {} error {}", groupInstanceId, vertexByProperty.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(vertexByProperty.right().value());
- }
- UUID uuid = UUID.randomUUID();
- TitanVertex ciVertex = vertexByProperty.left().value();
- ciVertex.property(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty(), uuid.toString());
-
- return StorageOperationStatus.OK;
- }
-
public void generateCustomizationUUID(GroupInstance groupInstance) {
UUID uuid = UUID.randomUUID();
groupInstance.setCustomizationUUID(uuid.toString());
@@ -465,8 +292,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
/**
* add property to resource instance
*
- * @param resourceInstanceProperty
- * @param resourceInstanceId
* @param index
* @return
*/
@@ -608,242 +433,7 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
}
- public Either<ComponentInstanceProperty, TitanOperationStatus> addPropertyToResourceInstance(ComponentInstanceProperty groupInstanceProperty, TitanVertex groupInstanceVertex, Integer index, String groupInstanceId) {
-
- String propertyId = groupInstanceProperty.getUniqueId();
- Either<PropertyData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
-
- if (findPropertyDefRes.isRight()) {
- TitanOperationStatus status = findPropertyDefRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
-
- String valueUniqueUid = groupInstanceProperty.getValueUniqueUid();
- if (valueUniqueUid == null) {
-
- PropertyData propertyData = findPropertyDefRes.left().value();
-
- ImmutablePair<TitanOperationStatus, String> isPropertyValueExists = propertyOperation.findPropertyValue(groupInstanceId, propertyId);
- if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) {
- log.trace("The property {} already added to the resource instance {}", propertyId, groupInstanceId);
- groupInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight());
- Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfGroupInstance(groupInstanceProperty, groupInstanceId);
- if (updatePropertyOfResourceInstance.isRight()) {
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR);
- return Either.right(updatePropertyOfResourceInstance.right().value());
- }
- return Either.right(TitanOperationStatus.OK);
- }
-
- if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) {
- log.trace("After finding property value of {} on componenet instance {}", propertyId, groupInstanceId);
- return Either.right(isPropertyValueExists.getLeft());
- }
-
- String innerType = null;
-
- PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
- String propertyType = propDataDef.getType();
- String value = groupInstanceProperty.getValue();
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
-
- if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
- SchemaDefinition def = propDataDef.getSchema();
- if (def == null) {
- log.debug("Schema doesn't exists for property of type {}", type);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- PropertyDataDefinition propDef = def.getProperty();
- if (propDef == null) {
- log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- innerType = propDef.getType();
- }
-
- log.trace("Before validateAndUpdatePropertyValue");
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(status);
- }
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value());
- log.trace("After validateAndUpdatePropertyValue. isValid = {}", isValid);
-
- String newValue = value;
- if (isValid.isRight()) {
- Boolean res = isValid.right().value();
- if (res == false) {
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- } else {
- Object object = isValid.left().value();
- if (object != null) {
- newValue = object.toString();
- }
- }
-
- String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(groupInstanceId, index);
- PropertyValueData propertyValueData = new PropertyValueData();
- propertyValueData.setUniqueId(uniqueId);
- propertyValueData.setValue(newValue);
-
- log.trace("Before validateAndUpdateRules");
- ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProperty.getRules(), innerType, allDataTypes.left().value(), false);
- log.debug("After validateAndUpdateRules. pair = {} ", pair);
- if (pair.getRight() != null && pair.getRight() == false) {
- BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProperty.getName(), propertyType);
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- propertyOperation.addRulesToNewPropertyValue(propertyValueData, groupInstanceProperty, groupInstanceId);
-
- log.trace("Before adding property value to graph {}", propertyValueData);
- Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class);
- log.trace("After adding property value to graph {}", propertyValueData);
-
- if (createNodeResult.isRight()) {
- TitanOperationStatus operationStatus = createNodeResult.right().value();
- return Either.right(operationStatus);
- }
- propertyValueData = createNodeResult.left().value();
-
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null);
-
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus);
- return Either.right(operationStatus);
- }
-
- TitanOperationStatus edgeResult = titanGenericDao.createEdge(groupInstanceVertex, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null);
-
- if (edgeResult != TitanOperationStatus.OK) {
- log.error("Failed to associate resource instance {} property value {} in graph. status is {}", groupInstanceId, uniqueId, edgeResult);
- return Either.right(edgeResult);
- }
-
- ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, groupInstanceProperty);
- log.debug("The returned ResourceInstanceProperty is {} ", propertyValueResult);
-
- return Either.left(propertyValueResult);
- } else {
- log.debug("property value already exists.");
- return Either.right(TitanOperationStatus.ALREADY_EXIST);
- }
-
- }
-
- public Either<GroupInstance, TitanOperationStatus> addGroupInstanceToComponentInstance(String componentInstanceId, boolean isCreateLogicaName, GroupInstance groupInstance) {
- log.debug("Going to create group instance {} in componentInstance {}", groupInstance, componentInstanceId);
- Either<TitanVertex, TitanOperationStatus> metadataVertex = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId);
- if (metadataVertex.isRight()) {
- TitanOperationStatus status = metadataVertex.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
- Either<TitanVertex, TitanOperationStatus> addComponentInstanceToContainerComponent = addGroupInstanceToContainerComponent(metadataVertex.left().value(), componentInstanceId, isCreateLogicaName, groupInstance);
-
- if (addComponentInstanceToContainerComponent.isRight()) {
- TitanOperationStatus status = addComponentInstanceToContainerComponent.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
- TitanVertex ciVertex = addComponentInstanceToContainerComponent.left().value();
- Map<String, Object> properties = titanGenericDao.getProperties(ciVertex);
- GroupInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.GroupInstance.getName(), GraphElementTypeEnum.Node, properties, GroupInstanceData.class);
-
- GroupInstance createdResourceInstance = new GroupInstance(createdComponentInstance.getGroupDataDefinition());
-
- return Either.left(createdResourceInstance);
-
- }
-
- /**
- *
- * @param containerComponentId
- * @param containerNodeType
- * @param instanceNumber
- * @param isCreateLogicaName
- * @param componentInstance
- * @param compInstNodeType
- * @param metadataVertex
- * @return
- */
- public Either<TitanVertex, TitanOperationStatus> addGroupInstanceToContainerComponent(TitanVertex ciVertex, String componentInstanceId, boolean isCreateLogicaName, GroupInstance groupInstance) {
- TitanOperationStatus status = null;
- log.debug("Going to create group instance {} in component instance {}", groupInstance, componentInstanceId);
- String instOriginGroupId = groupInstance.getGroupUid();
- String logicalName = groupInstance.getName();
- if (isCreateLogicaName){
- String instanceName = (String) titanGenericDao.getProperty(ciVertex, GraphPropertiesDictionary.NORMALIZED_NAME.getProperty());
- logicalName = createGroupInstLogicalName(instanceName, groupInstance.getGroupName());
- }
-
- GroupInstanceData groupInstanceData = buildGroupInstanceData(groupInstance, componentInstanceId, logicalName);
- Either<TitanVertex, TitanOperationStatus> originVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), instOriginGroupId);
- if (originVertexEither.isRight()) {
- log.debug("Failed to fetch vertex of origin resource for id {} error {}", instOriginGroupId, originVertexEither.right().value());
- return Either.right(originVertexEither.right().value());
- }
- TitanVertex originVertex = originVertexEither.left().value();
-
- // String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty());
- String groupType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.TYPE.getProperty());
- // detectOriginType(originType, groupInstanceData, resourceType);
-
- log.trace("Before adding component instance to graph. componentInstanceData = {}", groupInstanceData);
- // groupInstanceData.getGroupDataDefinition().setGroupUid(groupType);
-
- Either<TitanVertex, TitanOperationStatus> createGIResult = titanGenericDao.createNode(groupInstanceData);
-
- log.debug("After adding component instance to graph. status is = {}", createGIResult);
-
- if (createGIResult.isRight()) {
- status = createGIResult.right().value();
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
- log.debug("Failed to create group instance node in graph. status is {}", status);
- return Either.right(status);
- }
- TitanVertex createdGroupInstanceVertex = createGIResult.left().value();
- TitanOperationStatus associateContainerRes = associateComponentInstanceToGroupInstance(ciVertex, createdGroupInstanceVertex, logicalName);
-
- String componentInstanceUniqueId = groupInstanceData.getUniqueId();
- if (associateContainerRes != TitanOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
- log.debug("Failed to associate container component {} to component instance {}. Status is {}", componentInstanceId, componentInstanceUniqueId, associateContainerRes);
- return Either.right(associateContainerRes);
- }
- // String originId = (String) titanGenericDao.getProperty(createdGroupInstanceVertex, GraphPropertiesDictionary.TYPE.getProperty());
-
- TitanOperationStatus associateToInstOriginComponent = associateToInstOriginGroup(createdGroupInstanceVertex, originVertex, instOriginGroupId);
- if (associateToInstOriginComponent != TitanOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance");
- log.debug("Failed to associate component instance {} to its origin component {}. Status is {}", componentInstanceUniqueId, groupInstanceData.getGroupDataDefinition().getGroupUid(), associateToInstOriginComponent);
- return Either.right(associateToInstOriginComponent);
- }
-
- // Capability instance with property values implementation
-
- if (status == null) {
- // ComponentInstance createdResourceInstance = new
- // ComponentInstance(createdComponentInstance.getComponentInstDataDefinition());
- //
- // String icon = (String) titanGenericDao.getProperty(originVertex,
- // GraphPropertiesDictionary.ICON.getProperty());
- // createdResourceInstance.setIcon(icon);
- return Either.left(createdGroupInstanceVertex);
- }
- return Either.right(status);
- }
private GroupInstanceData buildGroupInstanceData(GroupInstance groupInstance, String componentInstanceId, String logicalName) {
String ciOriginComponentUid = groupInstance.getGroupUid();
@@ -869,119 +459,9 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
return resourceInstanceData;
}
- @Override
- public String createGroupInstLogicalName(String instanceName, String groupName) {
-
- String logicalName = buildGroupInstanceLogicalName(instanceName, groupName);
-
- return logicalName;
- }
-
- private String buildGroupInstanceLogicalName(String instanceName, String groupName) {
- return ValidationUtils.normalizeComponentInstanceName(instanceName) + ".." + groupName;
- }
-
- /**
- * Make a relation between service to resource instance.
- *
- * @param containerCompIdData
- * @param componentInstanceData
- * @param logicalName
- * @return
- */
- private Either<GraphRelation, TitanOperationStatus> associateComponentInstanceToGroupInstance(UniqueIdData compInstIdData, GroupInstanceData groupInstanceData, String logicalName) {
- Map<String, Object> properties = new HashMap<String, Object>();
-
- properties.put(GraphPropertiesDictionary.NAME.getProperty(), logicalName);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(compInstIdData, groupInstanceData, GraphEdgeLabels.GROUP_INST, properties);
-
- log.debug("After associating container component {} to resource instance {} with logical name {}. Status is {}", compInstIdData.getUniqueId(), groupInstanceData.getUniqueId(), logicalName, createRelation);
-
- return createRelation;
- }
-
- private TitanOperationStatus associateComponentInstanceToGroupInstance(TitanVertex componentInstVertex, TitanVertex groupInstanceVertex, String logicalName) {
- Map<String, Object> properties = new HashMap<String, Object>();
-
- properties.put(GraphPropertiesDictionary.NAME.getProperty(), logicalName);
- TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstVertex, groupInstanceVertex, GraphEdgeLabels.GROUP_INST, properties);
-
- return createRelation;
- }
-
- private Either<GraphRelation, TitanOperationStatus> associateToInstOriginGroup(GroupInstanceData groupInstanceData, NodeTypeEnum compInstNodeType) {
-
- UniqueIdData groupIdData = new UniqueIdData(compInstNodeType, groupInstanceData.getGroupDataDefinition().getGroupUid());
-
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupInstanceData, groupIdData, GraphEdgeLabels.INSTANCE_OF, null);
-
- log.debug("After associating group instance {} to group {}. status is {}", groupInstanceData.getUniqueId(), groupInstanceData.getGroupDataDefinition().getGroupUid(), createRelation);
-
- return createRelation;
- }
-
- private TitanOperationStatus associateToInstOriginGroup(TitanVertex groupInstanceVertex, TitanVertex originVertex, String originId) {
-
- TitanOperationStatus createRelation = titanGenericDao.createEdge(groupInstanceVertex, originVertex, GraphEdgeLabels.INSTANCE_OF, null);
-
- log.debug("After associating group instance {} to group {}. status is {}", groupInstanceVertex, originId, createRelation);
-
- return createRelation;
- }
-
- public Either<List<GroupProperty>, TitanOperationStatus> getGroupInstanceProperties(GroupInstance groupInstance, GroupDefinition groupDefinition) {
-
- // 1. Go over each instance
- // 1.1 get all properties of from the parents of the instance
- // 1.2 get all updated properties
- // 1.3 find all instances included in the parent of this instance and
- // run this method on them.
- String groupInstanceId = groupInstance.getUniqueId();
- if (log.isDebugEnabled())
- log.debug("Going to update properties of group instance {}", groupInstanceId);
- String groupUid = groupInstance.getGroupUid();
- List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
-
- if (log.isDebugEnabled())
- log.debug("After getting properties of group {} . Number of properties is {}", groupUid, (properties == null ? 0 : properties.size()));
- List<GroupProperty> resourceInstancePropertyList = new ArrayList<>();
- if (properties != null && false == properties.isEmpty()) {
-
- // TODO: WE MAY HAVE INDIRECT PROPERTY VALUE ALSO IN CASE NO
- // PROPERTY ON THIS COMPONENT
-
- // String resourceInstanceUid = resourceInstance.getUniqueId();
-
- for (GroupProperty propertyDefinition : properties) {
-
- String defaultValue = propertyDefinition.getDefaultValue();
- String value = defaultValue;
- String valueUid = null;
-
- // String propertyId = propertyDefinition.getUniqueId();
-
- GroupProperty resourceInstanceProperty = new GroupProperty(propertyDefinition, value, valueUid);
-
- // resourceInstanceProperty.setPath(cloneList(path));
-
- // TODO: currently ignore constraints since they are not inuse
- // and cause to error in convertion to object.
- resourceInstanceProperty.setConstraints(null);
-
- resourceInstancePropertyList.add(resourceInstanceProperty);
-
- }
-
- }
-
- return Either.left(resourceInstancePropertyList);
- }
-
/**
* update value of attribute on resource instance
*
- * @param resourceInstanceProerty
- * @param resourceInstanceId
* @return
*/
public Either<PropertyValueData, TitanOperationStatus> updatePropertyOfGroupInstance(ComponentInstanceProperty groupInstanceProerty, String groupInstanceId) {
@@ -1207,68 +687,7 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
}
}
- /**
- * Associate artifacts to a given group
- *
- * @param groupId
- * @param artifactsId
- * @param inTransaction
- * @return
- */
- public Either<GroupInstance, StorageOperationStatus> associateArtifactsToGroupInstance(String groupId, List<String> artifactsId) {
-
- Either<GroupInstance, StorageOperationStatus> result = null;
-
- Either<GroupInstance, TitanOperationStatus> titanRes = this.associateArtifactsToGroupInstanceOnGraph(groupId, artifactsId);
-
- if (titanRes.isRight()) {
- StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value());
- result = Either.right(status);
- }
-
- result = Either.left(titanRes.left().value());
- return result;
-
- }
-
- public Either<GroupInstance, TitanOperationStatus> associateArtifactsToGroupInstanceOnGraph(String groupInstanceId, List<String> artifactsId) {
-
- if (artifactsId == null || artifactsId.isEmpty()) {
- return Either.right(TitanOperationStatus.OK);
- }
-
- for (String artifactId : artifactsId) {
- Either<ArtifactData, TitanOperationStatus> findArtifactRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
- if (findArtifactRes.isRight()) {
- TitanOperationStatus status = findArtifactRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- String description = "Failed to associate group " + groupInstanceId + " to artifact " + artifactId + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(status);
- }
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), findArtifactRes.left().value().getLabel());
-
- GraphNode groupData = new UniqueIdData(NodeTypeEnum.GroupInstance, groupInstanceId);
- Either<GraphRelation, TitanOperationStatus> addArtifactsRefResult = titanGenericDao.createRelation(groupData, findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, props);
-
- if (addArtifactsRefResult.isRight()) {
- TitanOperationStatus status = addArtifactsRefResult.right().value();
- String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(status);
- }
- }
-
- Either<GroupInstance, TitanOperationStatus> groupFromGraph = this.getGroupInstanceFromGraph(groupInstanceId, true, false);
-
- return groupFromGraph;
- }
-
- public Either<GroupInstance, TitanOperationStatus> getGroupInstanceFromGraph(String uniqueId, boolean skipProperties, boolean skipArtifacts) {
+ private Either<GroupInstance, TitanOperationStatus> getGroupInstanceFromGraph(String uniqueId, boolean skipProperties, boolean skipArtifacts) {
Either<GroupInstance, TitanOperationStatus> result = null;
@@ -1337,20 +756,20 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
private void buildGroupInstanceFromGroup(GroupInstance groupInstance, GroupDefinition groupDefinition, Map<String, PropertyValueData> groupInstancePropertyValues) {
- groupInstance.setGroupName(groupDefinition.getName());
- groupInstance.setInvariantUUID(groupDefinition.getInvariantUUID());
- groupInstance.setDescription(groupDefinition.getDescription());
- groupInstance.setVersion(groupDefinition.getVersion());
- groupInstance.setArtifacts(groupDefinition.getArtifacts());
- groupInstance.setArtifactsUuid(groupDefinition.getArtifactsUuid());
- groupInstance.setType(groupDefinition.getType());
- groupInstance.setGroupUUID(groupDefinition.getGroupUUID());
-
- List<GroupInstanceProperty> groupInstanceProperties = groupDefinition.convertToGroupProperties()
- //converts List of GroupProperties to List of GroupInstanceProperties and updates it with group instance property data
- .stream().map(p->getUpdatedConvertedProperty(p, groupInstancePropertyValues)).collect(Collectors.toList());
- groupInstance.convertFromGroupInstancesProperties(groupInstanceProperties);
-}
+ groupInstance.setGroupName(groupDefinition.getName());
+ groupInstance.setInvariantUUID(groupDefinition.getInvariantUUID());
+ groupInstance.setDescription(groupDefinition.getDescription());
+ groupInstance.setVersion(groupDefinition.getVersion());
+ groupInstance.setArtifacts(groupDefinition.getArtifacts());
+ groupInstance.setArtifactsUuid(groupDefinition.getArtifactsUuid());
+ groupInstance.setType(groupDefinition.getType());
+ groupInstance.setGroupUUID(groupDefinition.getGroupUUID());
+
+ List<GroupInstanceProperty> groupInstanceProperties = groupDefinition.convertToGroupProperties()
+ //converts List of GroupProperties to List of GroupInstanceProperties and updates it with group instance property data
+ .stream().map(p -> getUpdatedConvertedProperty(p, groupInstancePropertyValues)).collect(Collectors.toList());
+ groupInstance.convertFromGroupInstancesProperties(groupInstanceProperties);
+ }
private GroupInstanceProperty getUpdatedConvertedProperty(GroupProperty groupProperty, Map<String, PropertyValueData> groupInstancePropertyValues){
@@ -1401,14 +820,11 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
@Override
public StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
- StorageOperationStatus result = null;
-
return this.dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact);
}
- @Override
- public StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
+ private StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
Either<List<GroupInstance>, StorageOperationStatus> allGroupsFromGraph = getAllGroupInstances(componentId, componentTypeEnum);
if (allGroupsFromGraph.isRight()) {
@@ -1461,212 +877,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
return StorageOperationStatus.OK;
}
- @Override
- public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValues(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties, Boolean inTransaction) {
-
- Either<GroupInstance, StorageOperationStatus> updateRes = Either.left(oldGroupInstance);
- try{
- if(!CollectionUtils.isEmpty(newProperties)){
- updateRes = updateGroupInstancePropertyValuesOnGraph(oldGroupInstance, newProperties);
- }
- }catch(Exception e){
- log.debug("The Exception occured during update of group instance {} property values. The message is {}. ", oldGroupInstance.getName(), e.getMessage(), e);
- updateRes = Either.right(StorageOperationStatus.GENERAL_ERROR);
- }finally {
- handleTransactionCommitRollback(inTransaction, updateRes);
- }
- return updateRes;
- }
-
- private Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValuesOnGraph( GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties ) {
- Either<GroupInstance, StorageOperationStatus> updateRes = null;
- Either<Integer, StorageOperationStatus> nodeUpdateRes = null;
- Vertex groupInstanceVertex = null;
- Either<Vertex, StorageOperationStatus> groupInstanceVertexRes;
- Map<String, Vertex> existingPropertyValueVertices = new HashMap<>();
- Map<String, Vertex> existingPropertyVertices = new HashMap<>();
- groupInstanceVertexRes = getVertexFromGraph(GraphPropertiesDictionary.UNIQUE_ID.getProperty(),oldGroupInstance.getUniqueId());
- try{
- if (groupInstanceVertexRes.isRight()) {
- log.debug("Failed to fetch group instance vertex {} from graph. ", oldGroupInstance.getName());
- updateRes = Either.right(groupInstanceVertexRes.right().value());
- } else {
- groupInstanceVertex = groupInstanceVertexRes.left().value();
- findExistingPropertyValueVertices(groupInstanceVertex, existingPropertyValueVertices);
- nodeUpdateRes = handlePropertyValues(oldGroupInstance, oldGroupInstance.getPropertyValueCounter(), newProperties, groupInstanceVertex, existingPropertyValueVertices, existingPropertyVertices);
- if(nodeUpdateRes.isRight()){
- log.debug("Failed to handle property values of group instance {}. ", oldGroupInstance.getName());
- updateRes = Either.right(nodeUpdateRes.right().value());
- } else {
- updateRes = updateGroupInstanceVertexAndGetUpdatedGroupInstance(groupInstanceVertex, nodeUpdateRes.left().value(), oldGroupInstance);
- }
- }
- } catch(Exception e){
- log.debug("The Exception occured during update group instance {} property values on graph. The message is {}. ", oldGroupInstance.getName(), e.getMessage(), e);
- updateRes = Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- return updateRes;
- }
-
- private Either<Integer, StorageOperationStatus> handlePropertyValues(GroupInstance oldGroupInstance, Integer propertyValueCounter, List<GroupInstanceProperty> newProperties, Vertex groupInstanceVertex,
- Map<String, Vertex> existingPropertyValueVertices, Map<String, Vertex> existingPropertyVertices) {
-
- Either<Integer, StorageOperationStatus> nodeHandleRes = null;
- int currCounter = propertyValueCounter;
- for(GroupInstanceProperty currProperty : newProperties){
- nodeHandleRes = handlePropertyValueNode(oldGroupInstance, currCounter, currProperty, groupInstanceVertex, existingPropertyValueVertices, existingPropertyVertices);
- if(nodeHandleRes.isRight()){
- break;
- }
- currCounter = nodeHandleRes.left().value();
- }
- return nodeHandleRes;
- }
-
- private Either<GroupInstance, StorageOperationStatus> updateGroupInstanceVertexAndGetUpdatedGroupInstance( Vertex groupInstanceVertex, Integer propertyValueCounter, GroupInstance oldGroupInstance) {
-
- TitanOperationStatus status;
- Either<GroupInstance, StorageOperationStatus> actionResult;
- status = updateGroupInstanceVertex(groupInstanceVertex, propertyValueCounter);
- if(status != TitanOperationStatus.OK){
- log.debug("Failed to update group instance {}. ", oldGroupInstance.getName());
- actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }else{
- Either<GroupInstance, TitanOperationStatus> updatedGroupInstanceRes = getGroupInstanceFromGraph(oldGroupInstance.getUniqueId(), false, false);
- if(updatedGroupInstanceRes.isRight()){
- status = updatedGroupInstanceRes.right().value();
- log.debug("Failed to get updated group instance {}. Status is {}. ", oldGroupInstance.getName(), status);
- actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }else{
- actionResult = Either.left(updatedGroupInstanceRes.left().value());
- }
- }
- return actionResult;
- }
-
- private Either<Integer, StorageOperationStatus> handlePropertyValueNode(GroupInstance oldGroupInstance, Integer propertyValueCounter, GroupInstanceProperty currProperty, Vertex groupInstanceVertex, Map<String, Vertex> existingPropertyValueVertices, Map<String, Vertex> existingPropertyVertices) {
-
- String groupInstanceName = oldGroupInstance.getName();
- TitanOperationStatus updateStatus;
- TitanOperationStatus addStatus;
- Vertex propertyValueVertex;
- String propertyValueId;
- propertyValueId = currProperty.getValueUniqueUid();
- Either<Integer, StorageOperationStatus> actionResult = null;
- if(existingPropertyValueVertices.containsKey(propertyValueId)){
- updateStatus = updatePropertyValueVertex(existingPropertyValueVertices.get(propertyValueId), currProperty);
- if(updateStatus != TitanOperationStatus.OK){
- log.debug("Failed to update property value {} of group instance {}. ", currProperty.getName(), groupInstanceName);
- actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateStatus));
- }
- }
- else{
- if(MapUtils.isEmpty(existingPropertyVertices)){
- findExistingPropertyVertices(existingPropertyVertices, groupInstanceVertex);
- }
- propertyValueVertex = existingPropertyVertices.get(currProperty.getUniqueId());
- addStatus = addPropertyValueNodeToGroupInstance(currProperty, groupInstanceVertex, propertyValueVertex, oldGroupInstance.getUniqueId(), ++propertyValueCounter);
- if(addStatus != TitanOperationStatus.OK){
- log.debug("Failed to add property value {} to group instance {}. ", currProperty.getName(), groupInstanceName);
- actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addStatus));
- }
- }
- if(actionResult == null){
- actionResult = Either.left(propertyValueCounter);
- }
- return actionResult;
- }
-
- @SuppressWarnings("unchecked")
- private Either<Vertex, StorageOperationStatus> getVertexFromGraph(String uniqueKeyName, String uniqueId) {
-
- Either<Vertex, StorageOperationStatus> actionResult = null;
- try{
- Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph();
- Iterable<TitanVertex> vertices = null;
- if (graph.isRight()) {
- log.debug("Failed to get graph. Status is {}", graph.right().value());
- actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value()));
- }
- if(actionResult == null){
- TitanGraph tGraph = graph.left().value();
- vertices = tGraph.query().has(uniqueKeyName, uniqueId).vertices();
- if (vertices == null || vertices.iterator() == null || !vertices.iterator().hasNext()) {
- log.debug("Failed to get nodes from graph for type {} for id = {}", NodeTypeEnum.GroupInstance, uniqueId);
- actionResult = Either.right(StorageOperationStatus.NOT_FOUND);
- }
- }
- if(actionResult == null && vertices != null){
- actionResult = Either.left(vertices.iterator().next());
- }
- } catch(Exception e){
- log.debug("The Exception occured during get vertex {} from graph. The message is {}. ", uniqueId, e.getMessage(), e);
- }
- return actionResult;
- }
-
- private void findExistingPropertyValueVertices(Vertex groupInstanceVertex, Map<String, Vertex> existingPropertyValueVertices) {
- Iterator<Edge> propertyValueEdges = groupInstanceVertex.edges(Direction.OUT, GraphEdgeLabels.PROPERTY_VALUE.getProperty());
- Vertex propertyValueVertex;
- while(propertyValueEdges.hasNext()){
- propertyValueVertex = propertyValueEdges.next().inVertex();
- existingPropertyValueVertices.put((String) propertyValueVertex.property(GraphPropertiesDictionary.UNIQUE_ID.getProperty()).value(), propertyValueVertex);
- }
- }
-
- private void findExistingPropertyVertices(Map<String, Vertex> existingPropertyVertices, Vertex groupInstanceVertex) {
- Vertex groupVertex = groupInstanceVertex.edges(Direction.OUT, GraphEdgeLabels.INSTANCE_OF.getProperty()).next().inVertex();
- Vertex groupTypeVertex = groupVertex.edges(Direction.OUT, GraphEdgeLabels.TYPE_OF.getProperty()).next().inVertex();
- Iterator<Edge> groupTypePropertiesIterator = groupTypeVertex.edges(Direction.OUT, GraphEdgeLabels.PROPERTY.getProperty());
- while(groupTypePropertiesIterator.hasNext()){
- Vertex propertyValueVertex = groupTypePropertiesIterator.next().inVertex();
- existingPropertyVertices.put((String) propertyValueVertex.property(GraphPropertiesDictionary.UNIQUE_ID.getProperty()).value(), propertyValueVertex);
- }
- }
-
- private TitanOperationStatus addPropertyValueNodeToGroupInstance(GroupInstanceProperty currProperty, Vertex groupInstanceVertex, Vertex propertyVertex, String groupInstanceId, int index) {
- TitanOperationStatus status = null;
- TitanVertex propertyValueVertex = null;
- PropertyValueData newPropertyValue = new PropertyValueData();
- Long creationTime = System.currentTimeMillis();
- newPropertyValue.setModificationTime(creationTime);
- newPropertyValue.setCreationTime(creationTime);
- newPropertyValue.setUniqueId(UniqueIdBuilder.buildGroupPropertyValueUid(groupInstanceId, index));
- newPropertyValue.setValue(currProperty.getValue());
- newPropertyValue.setType(currProperty.getType());
- Either<TitanVertex, TitanOperationStatus> propertyValueNodeRes = titanGenericDao.createNode(newPropertyValue);
- if(propertyValueNodeRes.isRight()){
- status = propertyValueNodeRes.right().value();
- }
- if(status == null){
- propertyValueVertex = propertyValueNodeRes.left().value();
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.PROPERTY_NAME.getProperty(), currProperty.getName());
- status = titanGenericDao.createEdge(groupInstanceVertex, propertyValueVertex, GraphEdgeLabels.PROPERTY_VALUE, props);
- }
- if(status == TitanOperationStatus.OK){
- status = titanGenericDao.createEdge(propertyValueVertex, propertyVertex, GraphEdgeLabels.PROPERTY_IMPL, null);
- }
- return status;
- }
-
- private TitanOperationStatus updatePropertyValueVertex(Vertex propertyValueVertex, GroupInstanceProperty property) {
- PropertyValueData propertyValue = new PropertyValueData();
- propertyValue.setUniqueId(property.getValue());
- propertyValue.setModificationTime(System.currentTimeMillis());
- propertyValue.setType(property.getType());
- propertyValue.setValue(property.getValue());
- return titanGenericDao.updateVertex(propertyValue, propertyValueVertex);
- }
-
- private TitanOperationStatus updateGroupInstanceVertex(Vertex groupInstanceVertex, int propertyValueCounter) {
- GroupInstanceData groupInstanceData = new GroupInstanceData();
- groupInstanceData.getGroupDataDefinition().setModificationTime(System.currentTimeMillis());
- groupInstanceData.getGroupDataDefinition().setCustomizationUUID(UUID.randomUUID().toString());
- groupInstanceData.getGroupDataDefinition().setPropertyValueCounter(propertyValueCounter);
- return titanGenericDao.updateVertex(groupInstanceData, groupInstanceVertex);
- }
-
private Either<Map<String, PropertyValueData>, TitanOperationStatus> getAllGroupInstancePropertyValuesData(GroupInstanceData groupInstData) {
Either<Map<String, PropertyValueData>, TitanOperationStatus> result = null;
@@ -1694,8 +904,4 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI
}
return result;
}
- @Override
- public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValues(GroupInstance groupInstance, List<GroupInstanceProperty> newProperties) {
- return updateGroupInstancePropertyValues(groupInstance, newProperties, false);
- }
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java
index 52bcae36db..02c5194da3 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java
@@ -71,10 +71,6 @@ import fj.data.Either;
@Component("group-operation")
public class GroupOperation extends AbstractOperation implements IGroupOperation {
- private static String ADDING_GROUP = "AddingGroup";
- private static String DELETING_GROUP = "DeletingGroup";
- private static String DELETING_ALL_GROUPS = "DeletingAllGroups";
- private static String ASSOCIATING_GROUP_TO_COMP_INST = "AssociatingGroupToComponentInstance";
private static Logger log = LoggerFactory.getLogger(GroupOperation.class.getName());
@@ -87,597 +83,18 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
@javax.annotation.Resource
private ApplicationDataTypeCache dataTypeCache;
- @javax.annotation.Resource
- protected ResourceOperation resourceOperation;
-
- @Override
- public Either<GroupData, TitanOperationStatus> addGroupToGraph(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition) {
-
- String groupTypeUid = groupDefinition.getTypeUid();
-
- if (groupTypeUid == null) {
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, "Group type id is empty", ErrorSeverity.ERROR);
- return Either.right(TitanOperationStatus.INVALID_ID);
- }
-
- ComponentMetadataData metaData = null;
- if (nodeTypeEnum == NodeTypeEnum.Resource) {
- metaData = new ResourceMetadataData();
- } else {
- metaData = new ServiceMetadataData();
- }
- metaData.getMetadataDataDefinition().setUniqueId(componentId);
-
- groupDefinition.setUniqueId(UniqueIdBuilder.buildGroupUniqueId(componentId, groupDefinition.getName()));
-
- int propertiesSize = groupDefinition.getProperties() == null ? 0 : groupDefinition.getProperties().size();
- groupDefinition.setPropertyValueCounter(propertiesSize);
-
- GroupData groupData = new GroupData(groupDefinition);
-
- TitanOperationStatus status = null;
- // Adding group data node to graph
- log.debug("Before adding group to graph {}", groupData.toString());
- Either<GroupData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(groupData, GroupData.class);
- log.debug("After adding group to graph {}", groupData.toString());
- if (createNodeResult.isRight()) {
- status = createNodeResult.right().value();
- log.error("Failed to add group {} to graph. status is {}", groupDefinition.getName(), status);
- return Either.right(status);
- }
-
- // Associate group to group type
- log.debug("Going to associate group {} to its groupType {}", groupDefinition.getName(), groupDefinition.getType());
- Either<GraphRelation, TitanOperationStatus> associateGroupTypeRes = associateGroupToGroupType(groupData, groupTypeUid);
- log.debug("After associating group {} to its groupType {}. status is {}", groupDefinition.getName(), groupDefinition.getType(), associateGroupTypeRes);
- if (associateGroupTypeRes.isRight()) {
- status = associateGroupTypeRes.right().value();
- String description = "Failed to associate group " + groupDefinition.getName() + " to its groupType " + groupDefinition.getType() + " in graph.";
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(status);
- }
-
- // Associate group to component RESOURCE/SERVICE/PRODUCT
- Either<GraphRelation, TitanOperationStatus> associateComponentRes = associateGroupToComponent(groupData, nodeTypeEnum, componentId);
- if (associateComponentRes.isRight()) {
- status = associateComponentRes.right().value();
- String description = "Failed to associate group " + groupDefinition.getName() + " to " + nodeTypeEnum.getName() + " " + componentId + ". status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(status);
- }
-
- Either<GroupTypeDefinition, TitanOperationStatus> groupTypeRes = groupTypeOperation.getGroupTypeByUid(groupDefinition.getTypeUid());
- if (groupTypeRes.isRight()) {
- TitanOperationStatus operationStatus = groupTypeRes.right().value();
- log.debug("Failed to find group type {}", groupDefinition.getTypeUid());
- if (operationStatus == TitanOperationStatus.NOT_FOUND) {
- return Either.right(TitanOperationStatus.INVALID_ID);
- }
- }
- GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
- // 1. find properties from group type
- List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
-
- // 2. check the properties exists in the group type.
- // 3. add parent unique id to the properties
- // 4. add node per group property which the group point to it and it
- // points to the parent unique id
-
- // Adding properties to group
- List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
-
- if (properties != null && false == properties.isEmpty()) {
-
- if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) {
- BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO);
- return Either.right(TitanOperationStatus.MATCH_NOT_FOUND);
- }
-
- Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p));
-
- Either<PropertyValueData, TitanOperationStatus> addPropertyResult = null;
- int i = 1;
- for (GroupProperty prop : properties) {
- addPropertyResult = addPropertyToGroup(groupData, prop, groupTypePropertiesMap.get(prop.getName()), i);
- if (addPropertyResult.isRight()) {
- status = addPropertyResult.right().value();
- String description = "Failed to associate group " + groupData.getUniqueId() + " to property " + prop.getName() + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(status);
- }
- i++;
- }
- }
-
- // Associate artifacts to group
- List<String> artifacts = groupDefinition.getArtifacts();
-
- Either<GroupDefinition, TitanOperationStatus> associateArtifactsToGroupOnGraph = associateArtifactsToGroupOnGraph(groupData.getGroupDataDefinition().getUniqueId(), artifacts);
- if (associateArtifactsToGroupOnGraph.isRight() && associateArtifactsToGroupOnGraph.right().value() != TitanOperationStatus.OK) {
- return Either.right(status);
- }
- /*
- * Either<GraphRelation, TitanOperationStatus> addArtifactsRefResult = null; if (artifacts != null) { for (String artifactId : artifacts) { Either<ArtifactData, TitanOperationStatus> findArtifactRes = titanGenericDao .getNode(UniqueIdBuilder
- * .getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class); if (findArtifactRes.isRight()) { status = findArtifactRes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { status =
- * TitanOperationStatus.INVALID_ID; } String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status; BeEcompErrorManager.getInstance().logInternalFlowError(
- * ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); }
- *
- * Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), findArtifactRes.left().value().getLabel());
- *
- * addArtifactsRefResult = titanGenericDao.createRelation( groupData, findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, props);
- *
- * if (addArtifactsRefResult.isRight()) { status = addArtifactsRefResult.right().value(); String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status;
- * BeEcompErrorManager.getInstance().logInternalFlowError( ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } } }
- */
-
- // Associate group to members
- // map of componentInstances <name: uniqueId>
- Map<String, String> members = groupDefinition.getMembers();
-
- if (members != null && false == members.isEmpty()) {
- Either<GraphRelation, TitanOperationStatus> addMembersRefResult = null;
- for (Entry<String, String> member : members.entrySet()) {
- if (member.getValue() == null || member.getValue().isEmpty()) {
- continue;
- }
- Either<ComponentInstanceData, TitanOperationStatus> findComponentInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), member.getValue(), ComponentInstanceData.class);
- if (findComponentInstanceRes.isRight()) {
- status = findComponentInstanceRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- String description = "Failed to find to find member of group " + member.getValue() + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(status);
- }
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), member.getKey());
- addMembersRefResult = titanGenericDao.createRelation(groupData, findComponentInstanceRes.left().value(), GraphEdgeLabels.GROUP_MEMBER, props);
-
- if (addMembersRefResult.isRight()) {
- status = addMembersRefResult.right().value();
- String description = "Failed to associate group " + groupData.getUniqueId() + " to component instance " + member.getValue() + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(status);
- }
- }
- }
-
- return Either.left(groupData);
- }
-
- private Either<PropertyDefinition, TitanOperationStatus> getPropertyDefFromGroupType(GroupProperty groupProperty) {
- Either<PropertyDefinition, TitanOperationStatus> ret;
- Either<GroupTypeDefinition, TitanOperationStatus> groupTypeRes = groupTypeOperation
- .getGroupTypeByUid(groupProperty.getParentUniqueId());
- if (groupTypeRes.isRight()) {
- TitanOperationStatus operationStatus = groupTypeRes.right().value();
- log.debug("Failed to find group type {}", groupProperty.getParentUniqueId());
- if (operationStatus == TitanOperationStatus.NOT_FOUND) {
- ret = Either.right(TitanOperationStatus.INVALID_ID);
- } else {
- ret = Either.right(operationStatus);
- }
- } else {
- GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value();
- List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties();
-
- Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream()
- .collect(Collectors.toMap(p -> p.getName(), p -> p));
- if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) {
- BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP,
- "group type does not have properties", ErrorSeverity.INFO);
- ret = Either.right(TitanOperationStatus.MATCH_NOT_FOUND);
- } else {
- PropertyDefinition propertyDefinition = groupTypePropertiesMap.get(groupProperty.getName());
- ret = Either.left(propertyDefinition);
- }
- }
- return ret;
- }
-
- /**
- * Updates GroupProperty Value
- * @param componentId TODO
- * @param groupId TODO
- * @param groupProperties
- * @param inTransaction TODO
- *
- * @return
- */
- public Either<List<GroupProperty>, StorageOperationStatus> updateGroupProperties(String componentId,
- String groupId, List<GroupProperty> groupProperties, boolean inTransaction) {
-
- Wrapper<Long> lastUpdateTimeWrapper = new Wrapper<>();
- TitanOperationStatus titanStatus = TitanOperationStatus.OK;
- Either<List<GroupProperty>, StorageOperationStatus> result = null;
- //Get Group Data
- final GroupData groupData;
- Either<GroupData, TitanOperationStatus> eitherGroupData = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupId, GroupData.class);
- if( eitherGroupData.isRight() ){
- log.debug("Error: Could not fetch group with groupId = {}", groupId);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherGroupData.right().value()));
- }
- else{
- groupData = eitherGroupData.left().value();
- }
-
- try {
- Optional<TitanOperationStatus> optionalError =
- //Stream of group properties to be updated
- groupProperties.stream().
- //updating each property and mapping to the TitanOperationStatus
- map(e -> updateGroupProperty(e, groupData, lastUpdateTimeWrapper)).
- //filtering in errors if there are such
- filter( e -> e != TitanOperationStatus.OK).
- //collect
- findFirst();
- if( optionalError.isPresent() ){
- titanStatus = optionalError.get();
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus));
- }
- else{
- result = updateLastModificationTimeOnVf(componentId, groupId, groupProperties, lastUpdateTimeWrapper);
- }
-
- }
- finally {
- handleTransactionCommitRollback(inTransaction, result);
- }
-
- return result;
- }
-
- private Either<List<GroupProperty>, StorageOperationStatus> updateLastModificationTimeOnVf(String componentId,
- String groupId, List<GroupProperty> groupProperties, Wrapper<Long> lastUpdateTimeWrapper) {
- Either<List<GroupProperty>, StorageOperationStatus> result;
- Either<Resource, StorageOperationStatus> eitherResource = resourceOperation.getResource(componentId);
- if( eitherResource.isRight() ){
- result = Either.right(eitherResource.right().value());
- }
- else{
- Either<ComponentMetadataData, StorageOperationStatus> eitherLastUpdateDateUpdatedOnResource = resourceOperation
- .updateComponentLastUpdateDateOnGraph(eitherResource.left().value(), NodeTypeEnum.Resource,
- lastUpdateTimeWrapper.getInnerElement(), true);
- if (eitherLastUpdateDateUpdatedOnResource.isLeft()) {
-
- groupProperties =
- //Group Stream From VF
- eitherResource.left().value().getGroups().stream().
- //Filter in Only the relevant group
- filter( e -> e.getUniqueId().equals(groupId)).
- //Get it
- findAny().get().
- //Get Group Properties from it
- convertToGroupProperties();
-
- result = Either.left(groupProperties);
- }
- else{
- result = Either.right(eitherLastUpdateDateUpdatedOnResource.right().value());
- }
- }
- return result;
- }
-
-
- private TitanOperationStatus updateGroupProperty(GroupProperty groupProperty, GroupData groupData,
- Wrapper<Long> lastUpdateTimeWrapper) {
- TitanOperationStatus titanStatus = TitanOperationStatus.OK;
- // PropertyValueData node does not exist
- if (StringUtils.isEmpty(groupProperty.getValueUniqueUid())) {
- // create new node
- if (!StringUtils.isEmpty(groupProperty.getValue())) {
- // Value does not exit and was not updated as well. no need
- // to do anything
- } else {
- titanStatus = addGroupPropertyToGraph(groupProperty, groupData, lastUpdateTimeWrapper);
-
- }
- }
-
- else {
- titanStatus = updateGroupPropertyInGraph(groupProperty, lastUpdateTimeWrapper);
- }
- return titanStatus;
- }
-
- private TitanOperationStatus updateGroupPropertyInGraph(GroupProperty groupProperty,
- Wrapper<Long> lastUpdateTimeWrapper) {
- TitanOperationStatus titanStatus;
- Either<PropertyValueData, TitanOperationStatus> eitherGroupPropertyValue = titanGenericDao.getNode(
- UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), groupProperty.getValueUniqueUid(),
- PropertyValueData.class);
- if (eitherGroupPropertyValue.isRight()) {
-
- titanStatus = eitherGroupPropertyValue.right().value();
-
- } else {
- PropertyValueData groupPropertyValue = eitherGroupPropertyValue.left().value();
- // Actual Update only if value changed
- if (!StringUtils.equals(groupPropertyValue.getValue(), groupProperty.getValue())) {
- long modificationTime = lastUpdateTimeWrapper.isEmpty() ? System.currentTimeMillis()
- : lastUpdateTimeWrapper.getInnerElement();
- groupPropertyValue.setValue(groupProperty.getValue());
- groupPropertyValue.setModificationTime(modificationTime);
- Either<PropertyValueData, TitanOperationStatus> eitherUpdateNode = titanGenericDao
- .updateNode(groupPropertyValue, PropertyValueData.class);
- if( eitherUpdateNode.isLeft() ){
- titanStatus = TitanOperationStatus.OK;
- lastUpdateTimeWrapper.setInnerElement(modificationTime);
- }
- else{
- titanStatus = eitherUpdateNode.right().value();
- }
-
- } else {
- titanStatus = TitanOperationStatus.OK;
- }
- }
- return titanStatus;
- }
-
- private TitanOperationStatus addGroupPropertyToGraph(GroupProperty groupProperty, GroupData groupData,
- Wrapper<Long> lastUpdateTimeWrapper) {
- PropertyDefinition propertyDefinition = null;
- TitanOperationStatus ret = TitanOperationStatus.OK;
- if (ret == TitanOperationStatus.OK) {
- Either<PropertyDefinition, TitanOperationStatus> eitherPropertyDefFromGroupType = getPropertyDefFromGroupType(
- groupProperty);
- if (eitherPropertyDefFromGroupType.isRight()) {
- log.debug("Error: Could not fetch group property from group Type with groupTypeId = {}",
- groupProperty.getParentUniqueId());
- ret = eitherPropertyDefFromGroupType.right().value();
- } else {
- propertyDefinition = eitherPropertyDefFromGroupType.left().value();
- }
- }
- if (ret == TitanOperationStatus.OK){
- final int groupPropCounter = groupData.getGroupDataDefinition().getPropertyValueCounter() + NumberUtils.INTEGER_ONE;
- Either<PropertyValueData, TitanOperationStatus> eitherAddPropertyToGroup = addPropertyToGroup(groupData,
- groupProperty, propertyDefinition, groupPropCounter);
-
- if( eitherAddPropertyToGroup.isLeft() ){
- ret = TitanOperationStatus.OK;
- if( lastUpdateTimeWrapper.isEmpty() ){
- lastUpdateTimeWrapper.setInnerElement(eitherAddPropertyToGroup.left().value().getCreationTime());
- }
- }
- else{
- ret = eitherAddPropertyToGroup.right().value();
- }
- if( ret == TitanOperationStatus.OK){
- groupData.getGroupDataDefinition().setPropertyValueCounter(groupPropCounter);
- Either<GroupData, TitanOperationStatus> updateNode = titanGenericDao .updateNode(groupData, GroupData.class);
- if( updateNode.isRight() ){
- ret = updateNode.right().value();
- }
- }
-
- }
- return ret;
- }
-
- public Either<PropertyValueData, TitanOperationStatus> addPropertyToGroup(GroupData groupData,
- GroupProperty groupProperty, PropertyDefinition prop, Integer index) {
-
- if (prop == null) {
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
-
- String propertyId = prop.getUniqueId();
- Either<PropertyData, TitanOperationStatus> findPropertyDefRes = titanGenericDao
- .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
-
- if (findPropertyDefRes.isRight()) {
- TitanOperationStatus status = findPropertyDefRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
-
- PropertyData propertyData = findPropertyDefRes.left().value();
-
- PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition();
- String propertyType = propDataDef.getType();
- String value = groupProperty.getValue();
-
- Either<String, TitanOperationStatus> checkInnerType = propertyOperation.checkInnerType(propDataDef);
- if (checkInnerType.isRight()) {
- TitanOperationStatus status = checkInnerType.right().value();
- return Either.right(status);
- }
-
- String innerType = checkInnerType.left().value();
-
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR);
- return Either.right(status);
-
- }
-
- log.debug("Before validateAndUpdatePropertyValue");
- Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value());
- log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid);
-
- String newValue = value;
- if (isValid.isRight()) {
- Boolean res = isValid.right().value();
- if (res == false) {
- return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT);
- }
- } else {
- Object object = isValid.left().value();
- if (object != null) {
- newValue = object.toString();
- }
- }
-
- String uniqueId = UniqueIdBuilder.buildGroupPropertyValueUid((String) groupData.getUniqueId(), index);
- PropertyValueData propertyValueData = new PropertyValueData();
- propertyValueData.setUniqueId(uniqueId);
- propertyValueData.setValue(newValue);
-
- log.debug("Before adding property value to graph {}", propertyValueData);
- Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class);
- log.debug("After adding property value to graph {}", propertyValueData);
-
- if (createNodeResult.isRight()) {
- TitanOperationStatus operationStatus = createNodeResult.right().value();
- return Either.right(operationStatus);
- }
-
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null);
-
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createRelResult.right().value();
- String description = "Failed to associate property value " + uniqueId + " to property " + propertyId + " in graph. status is " + operationStatus;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(operationStatus);
- }
-
- createRelResult = titanGenericDao.createRelation(groupData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null);
-
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createNodeResult.right().value();
- String description = "Failed to associate group " + groupData.getGroupDataDefinition().getName() + " to property value " + uniqueId + " in graph. Status is " + operationStatus;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(operationStatus);
- }
-
- return Either.left(createNodeResult.left().value());
- }
-
- private Either<GraphRelation, TitanOperationStatus> associateGroupToComponent(GroupData groupData, NodeTypeEnum nodeTypeEnum, String componentId) {
- UniqueIdData componentIdData = new UniqueIdData(nodeTypeEnum, componentId);
-
- log.debug("Before associating component {} to group {}", componentId, groupData);
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), groupData.getGroupDataDefinition().getName());
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(componentIdData, groupData, GraphEdgeLabels.GROUP, props);
- log.debug("After associating component {} to group {}. status is {}", componentId, groupData, createRelResult);
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createRelResult.right().value();
- log.debug("Failed to associate component {} to group {} in graph. Status is {}", componentId, groupData, operationStatus);
- return Either.right(operationStatus);
- }
-
- return Either.left(createRelResult.left().value());
- }
-
- private Either<GraphRelation, TitanOperationStatus> associateGroupToGroupType(GroupData groupData, String groupTypeUid) {
-
- UniqueIdData groupTypeIdData = new UniqueIdData(NodeTypeEnum.GroupType, groupTypeUid);
-
- log.debug("Before associating {} to group type {} (uid = {})", groupData, groupData.getGroupDataDefinition().getType(), groupTypeUid);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(groupData, groupTypeIdData, GraphEdgeLabels.TYPE_OF, null);
- log.debug("After associating {} to group type {} (uid = {}). Result is {}", groupData, groupData.getGroupDataDefinition().getType(), groupTypeUid, createRelResult);
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createRelResult.right().value();
- return Either.right(operationStatus);
- }
- return createRelResult;
- }
-
- @Override
- public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition) {
- return addGroup(nodeTypeEnum, componentId, groupDefinition, false);
- }
-
- @Override
- public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition, boolean inTransaction) {
-
- Either<GroupDefinition, StorageOperationStatus> result = null;
- try {
- Either<GroupData, TitanOperationStatus> addGroupRes = addGroupToGraph(nodeTypeEnum, componentId, groupDefinition);
- if (addGroupRes.isRight()) {
- TitanOperationStatus status = addGroupRes.right().value();
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- } else {
-
- GroupData groupData = addGroupRes.left().value();
- String groupUid = groupData.getGroupDataDefinition().getUniqueId();
- result = this.getGroup(groupUid, true);
-
- }
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph. Failed to add group {} to {}", groupDefinition.getName(), nodeTypeEnum.toString());
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
private GroupDefinition convertGroupDataToGroupDefinition(GroupData groupData) {
GroupDefinition newGroupDefinition = new GroupDefinition(groupData.getGroupDataDefinition());
return newGroupDefinition;
}
- public Either<GroupDefinition, StorageOperationStatus> getGroup(String uniqueId) {
- return getGroup(uniqueId, false);
- }
-
- @Override
- public Either<GroupDefinition, StorageOperationStatus> getGroup(String uniqueId, boolean inTransaction) {
-
- Either<GroupDefinition, StorageOperationStatus> result = null;
-
- try {
-
- Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(uniqueId);
-
- if (groupFromGraph.isRight()) {
- TitanOperationStatus status = groupFromGraph.right().value();
- log.debug("Failed to retrieve group {} from graph. Status is {}", uniqueId, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- } else {
- GroupDefinition groupDefinition = groupFromGraph.left().value();
- result = Either.left(groupDefinition);
- }
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public Either<GroupDefinition, TitanOperationStatus> getGroupFromGraph(String uniqueId) {
-
- return getGroupFromGraph(uniqueId, false, false, false);
-
- }
-
/**
* get members of group
*
* @param groupUniqueId
* @return
*/
- protected Either<Map<String, String>, TitanOperationStatus> getGroupMembers(String groupUniqueId) {
+ private Either<Map<String, String>, TitanOperationStatus> getGroupMembers(String groupUniqueId) {
Either<Map<String, String>, TitanOperationStatus> result = null;
@@ -711,7 +128,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
return result;
}
- public Either<GroupTypeDefinition, TitanOperationStatus> getGroupTypeOfGroup(String groupUniqueId) {
+ private Either<GroupTypeDefinition, TitanOperationStatus> getGroupTypeOfGroup(String groupUniqueId) {
Either<ImmutablePair<GroupTypeData, GraphEdge>, TitanOperationStatus> groupTypeRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.TYPE_OF, NodeTypeEnum.GroupType,
GroupTypeData.class);
@@ -726,9 +143,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
GroupTypeData groupTypeData = groupTypeRes.left().value().getKey();
- Either<GroupTypeDefinition, TitanOperationStatus> groupTypeByUid = groupTypeOperation.getGroupTypeByUid(groupTypeData.getGroupTypeDataDefinition().getUniqueId());
-
- return groupTypeByUid;
+ return groupTypeOperation.getGroupTypeByUid(groupTypeData.getGroupTypeDataDefinition().getUniqueId());
}
@@ -740,7 +155,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
* @param groupUid
* @return
*/
- public Either<List<GroupProperty>, TitanOperationStatus> getGroupProperties(String groupUid) {
+ private Either<List<GroupProperty>, TitanOperationStatus> getGroupProperties(String groupUid) {
List<GroupProperty> groupPropertiesList = new ArrayList<>();
@@ -824,466 +239,6 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
return Either.left(groupPropertiesList);
}
- public Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum) {
-
- return getAllGroupsFromGraph(componentId, componentTypeEnum, false, false, false);
-
- }
-
- @Override
- public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction) {
-
- Either<List<GroupDefinition>, StorageOperationStatus> result = null;
-
- try {
-
- Either<List<GroupDefinition>, TitanOperationStatus> allGroups = this.getAllGroupsFromGraph(componentId, compTypeEnum);
-
- if (allGroups.isRight()) {
- TitanOperationStatus status = allGroups.right().value();
- log.debug("Failed to retrieve all groups of component {} from graph. Status is {}", componentId, status);
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.OK;
- }
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- } else {
- List<GroupDefinition> groupsDefinition = allGroups.left().value();
- result = Either.left(groupsDefinition);
- }
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum) {
- return getAllGroups(componentId, compTypeEnum, false);
- }
-
- public Either<GroupData, TitanOperationStatus> deleteGroupFromGraph(String groupUniqueId) {
-
- Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupUniqueId);
- if (groupFromGraph.isRight()) {
- TitanOperationStatus status = groupFromGraph.right().value();
- log.debug("Cannot find group {} on graph. Status is {}", groupUniqueId, status);
- return Either.right(status);
- }
-
- GroupDefinition groupDefinition = groupFromGraph.left().value();
- // 1. delete all properties values nodes
- List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
- if (properties != null) {
- for (GroupProperty groupProperty : properties) {
- String propValueUniqueId = groupProperty.getValueUniqueUid();
-
- if (propValueUniqueId != null) {
- UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.PropertyValue, propValueUniqueId);
- Either<PropertyValueData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(uniqueIdData, PropertyValueData.class);
- if (deleteNode.isRight()) {
- TitanOperationStatus status = groupFromGraph.right().value();
- log.debug("Failed to delete property {} under group {} {} on graph. Status is {}", propValueUniqueId, groupDefinition.getName(), groupUniqueId, status.name());
- BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_GROUP, propValueUniqueId, status.name());
- return Either.right(status);
- } else {
- log.trace("Property {} was deleted from group {}" ,propValueUniqueId, groupDefinition.getName());
- }
- }
- }
- }
-
- // 2. delete the group node
- UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.Group, groupUniqueId);
- Either<GroupData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(uniqueIdData, GroupData.class);
- if (deleteNode.isRight()) {
- TitanOperationStatus status = groupFromGraph.right().value();
- log.debug("Failed to delete group {} with uid {} on graph. Status is {}", groupDefinition.getName(), groupUniqueId, status.name());
- BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_GROUP, groupUniqueId, status.name());
- return Either.right(status);
- } else {
- log.trace("Group {} was deleted from group", groupUniqueId);
- }
-
- GroupData groupData = deleteNode.left().value();
- return Either.left(groupData);
- }
-
- public Either<GroupDefinition, StorageOperationStatus> deleteGroup(String groupUniqueId) {
- return deleteGroup(groupUniqueId, false);
- }
-
- public Either<GroupDefinition, StorageOperationStatus> deleteGroup(String groupUniqueId, boolean inTransaction) {
-
- Either<GroupDefinition, StorageOperationStatus> result = null;
-
- try {
-
- Either<GroupData, TitanOperationStatus> deleteGroup = this.deleteGroupFromGraph(groupUniqueId);
-
- if (deleteGroup.isRight()) {
- TitanOperationStatus status = deleteGroup.right().value();
- log.debug("Failed to delete group {} from graph. Status is ", groupUniqueId, status.name());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- } else {
- GroupData groupData = deleteGroup.left().value();
- GroupDefinition groupDefinition = convertGroupDataToGroupDefinition(groupData);
- result = Either.left(groupDefinition);
- }
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public Either<List<GroupDefinition>, TitanOperationStatus> deleteAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum) {
-
- Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId, GraphEdgeLabels.GROUP, NodeTypeEnum.Group,
- GroupData.class);
-
- if (childrenNodes.isRight()) {
- TitanOperationStatus status = childrenNodes.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logBeFailedFindAllNodesError(DELETING_ALL_GROUPS, NodeTypeEnum.Group.name(), componentId, status.name());
- }
- return Either.right(status);
- }
-
- List<GroupDefinition> result = new ArrayList<>();
-
- List<ImmutablePair<GroupData, GraphEdge>> list = childrenNodes.left().value();
- if (list != null) {
- for (ImmutablePair<GroupData, GraphEdge> pair : list) {
- String uniqueId = pair.left.getGroupDataDefinition().getUniqueId();
- Either<GroupData, TitanOperationStatus> deleteGroupFromGraph = deleteGroupFromGraph(uniqueId);
- if (deleteGroupFromGraph.isRight()) {
- TitanOperationStatus status = deleteGroupFromGraph.right().value();
- BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_ALL_GROUPS, uniqueId, status.name());
- return Either.right(status);
- }
- GroupData groupData = deleteGroupFromGraph.left().value();
- GroupDefinition groupDefinition = convertGroupDataToGroupDefinition(groupData);
- result.add(groupDefinition);
- }
- }
-
- return Either.left(result);
- }
-
- @Override
- public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction) {
-
- Either<List<GroupDefinition>, StorageOperationStatus> result = null;
-
- try {
-
- Either<List<GroupDefinition>, TitanOperationStatus> allGroups = this.deleteAllGroupsFromGraph(componentId, compTypeEnum);
-
- if (allGroups.isRight()) {
- TitanOperationStatus status = allGroups.right().value();
- log.debug("Failed to delete all groups of component {} from graph. Status is {}", componentId, status);
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.OK;
- }
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- } else {
- List<GroupDefinition> groupsDefinition = allGroups.left().value();
- result = Either.left(groupsDefinition);
- }
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum) {
- return deleteAllGroups(componentId, compTypeEnum, false);
- }
-
- public Either<List<GroupDefinition>, StorageOperationStatus> prepareGroupsForCloning(org.openecomp.sdc.be.model.Component origResource, ImmutablePair<List<ComponentInstance>, Map<String, String>> cloneInstances) {
-
- List<GroupDefinition> groupsToCreate = new ArrayList<>();
- Either<List<GroupDefinition>, StorageOperationStatus> result = Either.left(groupsToCreate);
-
- List<GroupDefinition> groups = origResource.getGroups();
-
- if (groups != null) {
- // keep typeUid
- // keep artifacts uids
- // remove properties without valueUniqueId
- for (GroupDefinition groupDefinition : groups) {
-
- GroupDefinition gdToCreate = new GroupDefinition(groupDefinition);
- gdToCreate.setUniqueId(null);
- gdToCreate.setMembers(null);
-
- List<GroupProperty> properties = groupDefinition.convertToGroupProperties();
- if (properties != null) {
- // Take properties which was updated in the
- // group(getValueUniqueUid != null),
- // Then set null instead of the value(prepare for the
- // creation).
- List<GroupProperty> propertiesToUpdate = properties.stream().filter(p -> p.getValueUniqueUid() != null).map(p -> {
- p.setValueUniqueUid(null);
- return p;
- }).collect(Collectors.toList());
-
- gdToCreate.convertFromGroupProperties(propertiesToUpdate);
-
- }
-
- Map<String, String> members = groupDefinition.getMembers();
- if (cloneInstances != null) {
- List<ComponentInstance> createdInstances = cloneInstances.left;
- Map<String, String> oldCompUidToNew = cloneInstances.right;
- if (members != null && createdInstances != null) {
-
- Map<String, String> compInstIdToName = createdInstances.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p.getName()));
-
- Map<String, String> membersToCreate = new HashMap<>();
-
- for (String oldCompInstId : members.values()) {
- String newCompInstUid = oldCompUidToNew.get(oldCompInstId);
- if (newCompInstUid == null) {
- result = Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
- return result;
- }
- String newCompInstName = compInstIdToName.get(newCompInstUid);
- membersToCreate.put(newCompInstName, newCompInstUid);
- }
-
- gdToCreate.setMembers(membersToCreate);
- }
- }
-
- log.debug("The group definition for creation is {}", gdToCreate);
-
- groupsToCreate.add(gdToCreate);
- }
-
- }
-
- return result;
- }
-
- @Override
- public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(NodeTypeEnum nodeTypeEnum, String componentId, List<GroupDefinition> groups, boolean inTransaction) {
-
- List<GroupDefinition> createdGroups = new ArrayList<>();
-
- Either<List<GroupDefinition>, StorageOperationStatus> result = null;
-
- try {
-
- if (groups != null) {
- for (GroupDefinition groupDefinition : groups) {
- Either<GroupDefinition, StorageOperationStatus> addGroup = this.addGroup(nodeTypeEnum, componentId, groupDefinition, true);
- if (addGroup.isRight()) {
- StorageOperationStatus status = addGroup.right().value();
- result = Either.right(status);
- return result;
- }
-
- createdGroups.add(addGroup.left().value());
- }
- }
-
- result = Either.left(createdGroups);
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- @Override
- public Either<List<String>, TitanOperationStatus> getAssociatedGroupsToComponentInstanceFromGraph(String componentInstanceId) {
-
- List<String> groups = new ArrayList<>();
- Either<List<String>, TitanOperationStatus> result = Either.left(groups);
-
- Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), componentInstanceId, GraphEdgeLabels.GROUP_MEMBER,
- NodeTypeEnum.Group, GroupData.class);
-
- if (parentNodes.isRight()) {
- TitanOperationStatus status = parentNodes.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().logBeFailedFindParentError("FetchGroupMembers", componentInstanceId, status.name());
- }
- return Either.right(status);
- }
-
- List<ImmutablePair<GroupData, GraphEdge>> fetchedGroups = parentNodes.left().value();
- if (fetchedGroups != null) {
- List<String> list = fetchedGroups.stream().map(p -> p.left.getGroupDataDefinition().getUniqueId()).collect(Collectors.toList());
- groups.addAll(list);
- }
-
- return result;
-
- }
-
- @Override
- public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId, boolean inTransaction) {
-
- Either<List<String>, StorageOperationStatus> result = null;
-
- try {
-
- Either<List<String>, TitanOperationStatus> groups = this.getAssociatedGroupsToComponentInstanceFromGraph(componentInstanceId);
-
- if (groups.isRight()) {
- TitanOperationStatus status = groups.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.OK;
- }
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- List<String> list = groups.left().value();
-
- return Either.left(list);
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId) {
- return getAssociatedGroupsToComponentInstance(componentInstanceId, false);
- }
-
- @Override
- public Either<List<GraphRelation>, TitanOperationStatus> associateGroupsToComponentInstanceOnGraph(List<String> groups, String componentInstanceId, String compInstName) {
-
- List<GraphRelation> relations = new ArrayList<>();
- Either<List<GraphRelation>, TitanOperationStatus> result = Either.left(relations);
-
- if (groups != null && false == groups.isEmpty()) {
-
- UniqueIdData compInstData = new UniqueIdData(NodeTypeEnum.ResourceInstance, componentInstanceId);
-
- for (String groupId : groups) {
- UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupId);
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), compInstName);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupData, compInstData, GraphEdgeLabels.GROUP_MEMBER, props);
- if (createRelation.isRight()) {
- TitanOperationStatus status = createRelation.right().value();
- String description = "Failed to associate group " + groupData.getUniqueId() + " to component instance " + compInstName + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ASSOCIATING_GROUP_TO_COMP_INST, description, ErrorSeverity.ERROR);
- result = Either.right(status);
- break;
- }
- GraphRelation graphRelation = createRelation.left().value();
- relations.add(graphRelation);
- }
- } else {
- result = Either.right(TitanOperationStatus.OK);
- }
-
- return result;
- }
-
- public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, String compInstName) {
-
- return associateGroupsToComponentInstance(groups, componentInstanceId, compInstName, false);
- }
-
- @Override
- public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, String compInstName, boolean inTransaction) {
-
- StorageOperationStatus result = null;
-
- try {
- Either<List<GraphRelation>, TitanOperationStatus> either = this.associateGroupsToComponentInstanceOnGraph(groups, componentInstanceId, compInstName);
-
- if (either.isRight()) {
- TitanOperationStatus status = either.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.OK;
- }
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- return result;
- }
-
- result = StorageOperationStatus.OK;
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result != StorageOperationStatus.OK) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
@Override
public Either<List<GraphRelation>, TitanOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String artifactId) {
@@ -1479,49 +434,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
return Either.left(groups);
}
- @Override
- public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId, boolean inTransaction) {
-
- StorageOperationStatus result = null;
-
- try {
- Either<List<GraphRelation>, TitanOperationStatus> either = this.dissociateAllGroupsFromArtifactOnGraph(componentId, componentTypeEnum, artifactId);
-
- if (either.isRight()) {
- TitanOperationStatus status = either.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.OK;
- }
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- return result;
- }
-
- result = StorageOperationStatus.OK;
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result != StorageOperationStatus.OK) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId) {
-
- return dissociateAllGroupsFromArtifact(componentId, componentTypeEnum, artifactId, false);
- }
-
- @Override
- public TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
+ private TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
Either<List<GroupDefinition>, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false);
if (allGroupsFromGraph.isRight()) {
@@ -1602,12 +515,6 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
}
}
-
- }
-
- @Override
- public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) {
- return dissociateAndAssociateGroupsFromArtifact(componentId, componentTypeEnum, oldArtifactId, newArtifact, false);
}
private Either<List<ImmutablePair<String, String>>, TitanOperationStatus> getGroupArtifactsPairs(String groupUniqueId) {
@@ -1645,468 +552,6 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation
}
- public Either<List<GroupDefinition>, TitanOperationStatus> updateGroupVersionOnGraph(List<String> groupsUniqueId) {
-
- if (groupsUniqueId != null) {
-
- List<GroupDefinition> groups = new ArrayList<>();
- for (String groupUid : groupsUniqueId) {
- Either<GroupDefinition, TitanOperationStatus> either = updateGroupVersionOnGraph(groupUid);
- if (either.isRight()) {
- log.debug("Failed to update version of group {}", groupUid);
- return Either.right(either.right().value());
- }
- groups.add(either.left().value());
- }
- return Either.left(groups);
- }
-
- return Either.right(TitanOperationStatus.OK);
-
- }
-
- /**
- * update the group version of a given group. It also creates a new UUID.
- *
- * @param groupUniqueId
- * @return
- */
- public Either<GroupDefinition, TitanOperationStatus> updateGroupVersionOnGraph(String groupUniqueId) {
-
- Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupUniqueId, false, false, false);
-
- if (groupFromGraph.isRight()) {
- TitanOperationStatus status = groupFromGraph.right().value();
- return Either.right(status);
- } else {
- GroupDefinition groupDefinition = groupFromGraph.left().value();
- String version = groupDefinition.getVersion();
- String newVersion = increaseMajorVersion(version);
- Integer pvCounter = groupDefinition.getPropertyValueCounter();
-
- GroupData groupData = new GroupData();
- groupData.getGroupDataDefinition().setUniqueId(groupUniqueId);
- groupData.getGroupDataDefinition().setVersion(newVersion);
- groupData.getGroupDataDefinition().setPropertyValueCounter(pvCounter);
-
- String groupUUID = UniqueIdBuilder.generateUUID();
- groupData.getGroupDataDefinition().setGroupUUID(groupUUID);
-
- Either<GroupData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(groupData, GroupData.class);
- if (updateNode.isRight()) {
- return Either.right(updateNode.right().value());
- } else {
- groupFromGraph = this.getGroupFromGraph(groupUniqueId, false, false, false);
- return groupFromGraph;
- }
-
- }
- }
-
-
-
- /**
- * The version of the group is an integer. In order to support BC, we might get a version in a float format.
- *
- * @param version
- * @return
- */
- private String increaseMajorVersion(String version) {
-
- String[] versionParts = version.split(LifecycleOperation.VERSION_DELIMETER_REGEXP);
- Integer majorVersion = Integer.parseInt(versionParts[0]);
-
- majorVersion++;
-
- return String.valueOf(majorVersion);
-
- }
-
- public Either<GroupDefinition, TitanOperationStatus> associateArtifactsToGroupOnGraph(String groupId, List<String> artifactsId) {
-
- if (artifactsId == null || artifactsId.isEmpty()) {
- return Either.right(TitanOperationStatus.OK);
- }
-
- for (String artifactId : artifactsId) {
- Either<ArtifactData, TitanOperationStatus> findArtifactRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
- if (findArtifactRes.isRight()) {
- TitanOperationStatus status = findArtifactRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- String description = "Failed to associate group " + groupId + " to artifact " + artifactId + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(status);
- }
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), findArtifactRes.left().value().getLabel());
-
- GraphNode groupData = new UniqueIdData(NodeTypeEnum.Group, groupId);
- Either<GraphRelation, TitanOperationStatus> addArtifactsRefResult = titanGenericDao.createRelation(groupData, findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, props);
-
- if (addArtifactsRefResult.isRight()) {
- TitanOperationStatus status = addArtifactsRefResult.right().value();
- String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(status);
- }
- }
-
- Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true, false);
-
- return groupFromGraph;
- }
-
- public Either<GroupDefinition, TitanOperationStatus> associateMembersToGroupOnGraph(String groupId, Map<String, String> members) {
-
- if (members != null && false == members.isEmpty()) {
- Either<GraphRelation, TitanOperationStatus> addMembersRefResult = null;
- for (Entry<String, String> member : members.entrySet()) {
- Either<ComponentInstanceData, TitanOperationStatus> findComponentInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), member.getValue(), ComponentInstanceData.class);
- if (findComponentInstanceRes.isRight()) {
-
- TitanOperationStatus status = findComponentInstanceRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- String description = "Failed to find to find component instance group " + member.getValue() + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(status);
- }
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), member.getKey());
- GraphNode groupData = new UniqueIdData(NodeTypeEnum.Group, groupId);
- addMembersRefResult = titanGenericDao.createRelation(groupData, findComponentInstanceRes.left().value(), GraphEdgeLabels.GROUP_MEMBER, props);
- if (addMembersRefResult.isRight()) {
- TitanOperationStatus status = addMembersRefResult.right().value();
- String description = "Failed to associate group " + groupData.getUniqueId() + " to component instance " + member.getValue() + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(status);
- }
- }
- }
-
- Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, false, true);
-
- return groupFromGraph;
- }
-
- public Either<GroupDefinition, TitanOperationStatus> dissociateArtifactsFromGroupOnGraph(String groupId, List<String> artifactsId) {
-
- if (artifactsId == null || artifactsId.isEmpty()) {
- return Either.right(TitanOperationStatus.OK);
- }
-
- UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupId);
- for (String artifactId : artifactsId) {
-
- UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.Group, artifactId);
- Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF);
- log.trace("After dissociate group {} from artifact {}" ,groupId, artifactId);
-
- if (deleteRelation.isRight()) {
- TitanOperationStatus status = deleteRelation.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- String description = "Failed to diassociate group " + groupId + " from artifact " + artifactId + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(status);
- }
-
- }
-
- Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true, false);
-
- return groupFromGraph;
-
- }
-
- public Either<GroupDefinition, TitanOperationStatus> dissociateMembersFromGroupOnGraph(String groupId, Map<String, String> members) {
-
- if (members == null || members.isEmpty()) {
- return Either.right(TitanOperationStatus.OK);
- }
-
- UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupId);
- for (Entry<String, String> member : members.entrySet()) {
-
- UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.Group, member.getValue());
- Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_MEMBER);
- log.trace("After dissociate group {} from members {}" ,groupId, member.getValue());
-
- if (deleteRelation.isRight()) {
- TitanOperationStatus status = deleteRelation.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- String description = "Failed to diassociate group " + groupId + " from member " + member.getValue() + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR);
- return Either.right(status);
- }
-
- }
-
- Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true, false);
-
- return groupFromGraph;
-
- }
-
- /**
- * dissociate artifacts from a group. It do not delete the artifacts !!!
- *
- * @param groupId
- * @param artifactsId
- * @param inTransaction
- * @return
- */
- public Either<GroupDefinition, StorageOperationStatus> dissociateArtifactsFromGroup(String groupId, List<String> artifactsId, boolean inTransaction) {
-
- Either<GroupDefinition, StorageOperationStatus> result = null;
-
- try {
- Either<GroupDefinition, TitanOperationStatus> titanRes = this.dissociateArtifactsFromGroupOnGraph(groupId, artifactsId);
-
- if (titanRes.isRight()) {
- StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value());
- result = Either.right(storageOperationStatus);
- return result;
- }
-
- result = Either.left(titanRes.left().value());
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- public Either<GroupDefinition, StorageOperationStatus> dissociateMembersFromGroup(String groupId, Map<String, String> members, boolean inTransaction) {
-
- Either<GroupDefinition, StorageOperationStatus> result = null;
-
- try {
- Either<GroupDefinition, TitanOperationStatus> titanRes = this.dissociateMembersFromGroupOnGraph(groupId, members);
-
- if (titanRes.isRight()) {
- StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value());
- result = Either.right(storageOperationStatus);
- return result;
- }
-
- result = Either.left(titanRes.left().value());
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- /**
- * Associate artifacts to a given group
- *
- * @param groupId
- * @param artifactsId
- * @param inTransaction
- * @return
- */
- public Either<GroupDefinition, StorageOperationStatus> associateArtifactsToGroup(String groupId, List<String> artifactsId, boolean inTransaction) {
-
- Either<GroupDefinition, StorageOperationStatus> result = null;
-
- try {
-
- Either<GroupDefinition, TitanOperationStatus> titanRes = this.associateArtifactsToGroupOnGraph(groupId, artifactsId);
-
- if (titanRes.isRight()) {
- StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value());
- result = Either.right(status);
- }
-
- result = Either.left(titanRes.left().value());
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- /**
- * Associate artifacts to a given group
- *
- * @param groupId
- * @param artifactsId
- * @param inTransaction
- * @return
- */
- public Either<GroupDefinition, StorageOperationStatus> associateMembersToGroup(String groupId, Map<String, String> members, boolean inTransaction) {
-
- Either<GroupDefinition, StorageOperationStatus> result = null;
-
- try {
-
- Either<GroupDefinition, TitanOperationStatus> titanRes = this.associateMembersToGroupOnGraph(groupId, members);
-
- if (titanRes.isRight()) {
- StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value());
- result = Either.right(status);
- return result;
- }
-
- result = Either.left(titanRes.left().value());
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion(List<String> groupsId, boolean inTransaction) {
-
- Either<List<GroupDefinition>, StorageOperationStatus> result = null;
-
- try {
- Either<List<GroupDefinition>, TitanOperationStatus> updateGroupVersionOnGraph = this.updateGroupVersionOnGraph(groupsId);
-
- if (updateGroupVersionOnGraph.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateGroupVersionOnGraph.right().value()));
- return result;
- }
-
- result = Either.left(updateGroupVersionOnGraph.left().value());
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
- /**
- * This method updates group name
- * @param groupToUpdateFromUniqueId
- * @param newName
- * @param inTransaction
- * @return
- */
- public Either<GroupDefinition, StorageOperationStatus> updateGroupName(String groupToUpdateFromUniqueId,
- String newName, boolean inTransaction) {
- Either<GroupDefinition, StorageOperationStatus> result = null;
-
- try {
- //Update Name
- Either<GroupDefinition, TitanOperationStatus> updateGroupNameOnGraph = updateGroupNameOnGraph(
- groupToUpdateFromUniqueId, newName);
-
- if (updateGroupNameOnGraph.isRight()) {
- result = Either.right(
- DaoStatusConverter.convertTitanStatusToStorageStatus(updateGroupNameOnGraph.right().value()));
- }
- else{
- result = Either.left(updateGroupNameOnGraph.left().value());
- }
- return result;
-
- } finally {
- handleTransactionCommitRollback(inTransaction, result);
- }
- }
- @Override
- public Either<GroupDefinition, StorageOperationStatus> updateGroupName(String groupToUpdateFromUniqueId,
- String newName, GroupDefinition groupToUpdateTo, boolean inTransaction) {
- Either<GroupDefinition, StorageOperationStatus> result = null;
-
- try {
- //Update Name
- result = updateGroupName(groupToUpdateFromUniqueId, newName, true);
- return result;
-
- } finally {
- handleTransactionCommitRollback(inTransaction, result);
- }
- }
-
- private Either<GroupDefinition, TitanOperationStatus> updateGroupNameOnGraph(String uniqueId, String newName) {
-
- Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(uniqueId, false, false, false);
-
- if (groupFromGraph.isRight()) {
- TitanOperationStatus status = groupFromGraph.right().value();
- return Either.right(status);
- } else {
- GroupDefinition groupDefinition = groupFromGraph.left().value();
- String version = groupDefinition.getVersion();
- String newVersion = increaseMajorVersion(version);
- Integer pvCounter = groupDefinition.getPropertyValueCounter();
-
- GroupData groupData = new GroupData();
- groupData.getGroupDataDefinition().setUniqueId(uniqueId);
- groupData.getGroupDataDefinition().setVersion(newVersion);
- groupData.getGroupDataDefinition().setName(newName);
- groupData.getGroupDataDefinition().setPropertyValueCounter(pvCounter);
-
- Either<GroupData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(groupData, GroupData.class);
- if (updateNode.isRight()) {
- return Either.right(updateNode.right().value());
- } else {
- groupFromGraph = this.getGroupFromGraph(uniqueId, false, false, false);
- return groupFromGraph;
- }
- }
- }
-
-
@Override
public StorageOperationStatus validateAndUpdatePropertyValue(GroupProperty property) {
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java
index d3db95df65..782c78715f 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java
@@ -90,462 +90,12 @@ import fj.data.Either;
@Component("input-operation")
public class InputsOperation extends AbstractOperation implements IInputsOperation {
- private static final String GET_INPUT = "get_input";
-
- private static String ASSOCIATING_INPUT_TO_PROP = "AssociatingInputToComponentInstanceProperty";
-
private static Logger log = LoggerFactory.getLogger(InputsOperation.class.getName());
@Autowired
PropertyOperation propertyOperation;
- @Autowired
- private ComponentInstanceOperation componentInstanceOperation;
Gson gson = new Gson();
- /**
- * Delete specific input from component Although inputId is unique, pass also componentId as all other methods, and also check that the inputId is inside that componentId.
- */
- @Override
- public Either<InputDefinition, StorageOperationStatus> deleteInput(String inputId) {
- log.debug(String.format("Before deleting input: %s from graph", inputId));
- List<ComponentInstanceInput> inputsValueList = null;
- List<ComponentInstanceProperty> propertyList = new ArrayList<>();
-
- Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId);
-
- if (vertexService.isRight()) {
- log.debug("failed to fetch vertex of resource input for id = {}", inputId);
- TitanOperationStatus status = vertexService.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
-
- StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- return Either.right(convertTitanStatusToStorageStatus);
- }
- TitanVertex vertex = vertexService.left().value();
- Iterator<Edge> edgeIter = vertex.edges(Direction.IN, GraphEdgeLabels.INPUT.getProperty());
-
- if (edgeIter == null) {
- log.debug("No edges in graph for criteria");
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
- }
- String inputName = "";
- if (edgeIter != null) {
- while (edgeIter.hasNext()) {
- Edge edge = edgeIter.next();
- GraphEdge graphEdge = null;
-
- Map<String, Object> edgeProps = titanGenericDao.getProperties(edge);
- GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label());
- graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps);
-
- inputName = (String) graphEdge.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty());
-
- }
- }
-
-
- Either<List<ComponentInstanceInput>, TitanOperationStatus> inputsValueStatus = this.getComponentInstanceInputsByInputId(inputId);
- if(inputsValueStatus.isLeft()){
- inputsValueList = inputsValueStatus.left().value();
- if(!inputsValueList.isEmpty()){
- for(ComponentInstanceInput inputValue: inputsValueList){
- Either<InputValueData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InputValue), inputValue.getValueUniqueUid(), InputValueData.class);
- if (deleteNode.isRight()) {
- StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNode.right().value());
- return Either.right(convertTitanStatusToStorageStatus);
- }
- }
- }
- // US848813 delete service input that relates to VL / CP property
- } else {
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> propertyValueStatus = getComponentInstancePropertiesByInputId(inputId);
- if(propertyValueStatus.isLeft() && !propertyValueStatus.left().value().isEmpty()){
- //propertyList = propertyValueStatus.left().value();
- for(ComponentInstanceProperty propertyValue: propertyValueStatus.left().value()){
-
- String value = propertyValue.getValue();
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(value);
-
- resetInputName(mappedToscaTemplate, inputName);
-
- value = gson.toJson(mappedToscaTemplate);
- propertyValue.setValue(value);
- String compInstId = propertyValue.getComponentInstanceId();
- propertyValue.setRules(null);
-
- Either<PropertyValueData, TitanOperationStatus> eitherStatus = componentInstanceOperation.updatePropertyOfResourceInstance(propertyValue, compInstId, false);
-
- if (eitherStatus.isRight()) {
- log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", propertyValue, compInstId, eitherStatus.right().value().name());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
-
- } else {
- PropertyValueData propertyValueData = eitherStatus.left().value();
-
- ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, propertyValue);
-
- log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult);
-
- Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(propertyValue.getPath(), propertyValueData.getUniqueId(), propertyValue.getDefaultValue());
- if (findDefaultValue.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()));
-
- }
- String defaultValue = findDefaultValue.left().value();
- propertyValueResult.setDefaultValue(defaultValue);
- log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
-
- propertyValueResult.setComponentInstanceId(compInstId);
- propertyList.add(propertyValueResult);
-
-
- }
-
- }
- }
- }
- Either<InputsData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Input), inputId, InputsData.class);
- if (deleteNode.isRight()) {
- StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNode.right().value());
- return Either.right(convertTitanStatusToStorageStatus);
- } else {
- InputDefinition inputDefinition = this.convertInputDataToInputDefinition(deleteNode.left().value());
- inputDefinition.setInputs(inputsValueList);
- inputDefinition.setProperties(propertyList);
- inputDefinition.setName(inputName);
- return Either.left(inputDefinition);
- }
- }
-
- @Override
- public Either<List<InputDefinition>, TitanOperationStatus> addInputsToGraph(String componentId, NodeTypeEnum nodeType, Map<String, InputDefinition> inputs, Map<String, DataTypeDefinition> dataTypes) {
-
- List<InputDefinition> newInputs = new ArrayList<InputDefinition>();
- if (inputs != null) {
- for (Entry<String, InputDefinition> entry : inputs.entrySet()) {
-
- String inputName = entry.getKey();
- InputDefinition propertyDefinition = entry.getValue();
-
- StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(propertyDefinition, dataTypes);
- if (validateAndUpdateProperty != StorageOperationStatus.OK) {
- log.error("Property {} is invalid. Status is {}", propertyDefinition, validateAndUpdateProperty);
- return Either.right(TitanOperationStatus.INVALID_PROPERTY);
- }
-
- Either<InputsData, TitanOperationStatus> addPropertyToGraph = addInputToGraph(inputName, propertyDefinition, componentId, nodeType);
-
- if (addPropertyToGraph.isRight()) {
- return Either.right(addPropertyToGraph.right().value());
- }
- InputDefinition createdInputyDefinition = convertInputDataToInputDefinition(addPropertyToGraph.left().value());
- createdInputyDefinition.setName(inputName);
- createdInputyDefinition.setParentUniqueId(componentId);
- newInputs.add(createdInputyDefinition);
- }
- }
-
- return Either.left(newInputs);
- }
-
- @Override
- public TitanOperationStatus addInputsToGraph(TitanVertex metadata, String componentId, Map<String, InputDefinition> inputs, Map<String, DataTypeDefinition> dataTypes) {
-
- if (inputs != null) {
- for (Entry<String, InputDefinition> entry : inputs.entrySet()) {
-
- String inputName = entry.getKey();
- InputDefinition propertyDefinition = entry.getValue();
-
- StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(propertyDefinition, dataTypes);
- if (validateAndUpdateProperty != StorageOperationStatus.OK) {
- log.error("Property {} is invalid. Status is {} ", propertyDefinition, validateAndUpdateProperty);
- return TitanOperationStatus.INVALID_PROPERTY;
- }
-
- TitanOperationStatus addPropertyToGraph = addInputToGraph(metadata, inputName, propertyDefinition, componentId);
-
- if (!addPropertyToGraph.equals(TitanOperationStatus.OK)) {
- return addPropertyToGraph;
- }
-
- }
- }
-
- return TitanOperationStatus.OK;
- }
-
- @Override
- public Either<List<InputDefinition>, StorageOperationStatus> getInputsOfComponent(String compId, String fromName, int amount) {
- List<InputDefinition> inputs = new ArrayList<>();
- if ((fromName == null || fromName.isEmpty()) && amount == 0) {
-
- TitanOperationStatus status = findAllResourceInputs(compId, inputs);
-
- if (status != TitanOperationStatus.OK) {
- log.error("Failed to set inputs of resource {}. status is {}", compId, status);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
-
- } else {
-
- Either<TitanGraph, TitanOperationStatus> graphRes = titanGenericDao.getGraph();
- if (graphRes.isRight()) {
- log.error("Failed to retrieve graph. status is {}", graphRes);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphRes.right().value()));
- }
-
- TitanGraph titanGraph = graphRes.left().value();
- @SuppressWarnings("unchecked")
- Iterable<TitanVertex> vertices = titanGraph.query().has(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), compId).vertices();
- if (vertices == null || false == vertices.iterator().hasNext()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.INVALID_ID));
- }
-
- TitanVertex rootVertex = vertices.iterator().next();
- TitanVertexQuery<?> query;
- if (fromName == null || fromName.isEmpty())
- query = rootVertex.query().direction(Direction.OUT).labels(GraphEdgeLabels.INPUT.getProperty()).orderBy(GraphEdgePropertiesDictionary.NAME.getProperty(), Order.incr).limit(amount);
- else
- query = rootVertex.query().direction(Direction.OUT).labels(GraphEdgeLabels.INPUT.getProperty()).orderBy(GraphEdgePropertiesDictionary.NAME.getProperty(), Order.incr).has(GraphEdgePropertiesDictionary.NAME.getProperty(), Cmp.GREATER_THAN, fromName).limit(amount);
-
- Iterable<TitanEdge> edgesCreatorEges = query.edges();
-
- if (edgesCreatorEges == null) {
- log.debug("No edges in graph for criteria");
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
- }
- Iterator<TitanEdge> edgesCreatorIterator = edgesCreatorEges.iterator();
-
- if (edgesCreatorIterator != null) {
- while (edgesCreatorIterator.hasNext()) {
- Edge edge = edgesCreatorIterator.next();
- GraphEdge graphEdge = null;
-
- Map<String, Object> edgeProps = titanGenericDao.getProperties(edge);
- GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label());
- graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps);
-
- Vertex outgoingVertex = edge.inVertex();
- Map<String, Object> properties = titanGenericDao.getProperties(outgoingVertex);
- InputsData data = GraphElementFactory.createElement(NodeTypeEnum.Input.getName(), GraphElementTypeEnum.Node, properties, InputsData.class);
- String inputName = (String) graphEdge.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty());
- InputDefinition inputDefinition = this.convertInputDataToInputDefinition(data);
- inputDefinition.setName(inputName);
- inputDefinition.setParentUniqueId(compId);
-
- inputs.add(inputDefinition);
-
- }
- }
-
- }
- if (true == inputs.isEmpty()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
- }
-
- return Either.left(inputs);
-
- }
-
- @Override
- public Either<Map<String, InputDefinition>, StorageOperationStatus> deleteAllInputsAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) {
-
- Wrapper<TitanOperationStatus> errorWrapper;
- List<InputDefinition> inputs = new ArrayList<>();
- TitanOperationStatus findAllResourceAttribues = this.findNodeNonInheretedInputs(uniqueId, inputs);
- errorWrapper = (findAllResourceAttribues != TitanOperationStatus.OK) ? new Wrapper<>(findAllResourceAttribues) : new Wrapper<>();
-
- if (errorWrapper.isEmpty()) {
- for (InputDefinition inDef : inputs) {
- log.debug("Before deleting inputs from graph {}", inDef.getUniqueId());
- Either<InputsData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Input), inDef.getUniqueId(), InputsData.class);
- if (deleteNode.isRight()) {
- errorWrapper.setInnerElement(deleteNode.right().value());
- break;
- }
- }
- }
-
- if (errorWrapper.isEmpty()) {
- Map<String, InputDefinition> inputsMap = inputs.stream().collect(Collectors.toMap(e -> e.getName(), e -> e));
- return Either.left(inputsMap);
- } else {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(errorWrapper.getInnerElement()));
- }
-
- }
-
- @Override
- public Either<InputsData, StorageOperationStatus> addInput(String inputName, InputDefinition inputDefinition, String resourceId, NodeTypeEnum nodeType) {
-
- ComponentMetadataData componentMetadata = null;
-
- Either<InputsData, TitanOperationStatus> either = addInputToGraph(inputName, inputDefinition, resourceId, nodeType);
- if (either.isRight()) {
- StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value());
- return Either.right(storageStatus);
- }
- return Either.left(either.left().value());
- }
-
- @Override
- public Either<AttributeData, StorageOperationStatus> updateInput(String inputId, InputDefinition newInDef, Map<String, DataTypeDefinition> dataTypes) {
- // TODO Auto-generated method stub
- return null;
- }
-
- public Either<InputsData, TitanOperationStatus> addInputToGraph(String propertyName, InputDefinition inputDefinition, String componentId, NodeTypeEnum nodeType) {
-
- UniqueIdData from = new UniqueIdData(nodeType, componentId);
-
- List<PropertyConstraint> constraints = inputDefinition.getConstraints();
-
- inputDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, propertyName));
- InputsData inputData = new InputsData(inputDefinition, convertConstraintsToString(constraints));
-
- log.debug("Before adding property to graph {}", inputData);
- Either<InputsData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(inputData, InputsData.class);
- log.debug("After adding input to graph {}", inputData);
- if (createNodeResult.isRight()) {
- TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add input {} to graph. status is {}", propertyName, operationStatus);
- if(operationStatus == TitanOperationStatus.TITAN_SCHEMA_VIOLATION )
- return Either.right(TitanOperationStatus.ALREADY_EXIST);
- return Either.right(operationStatus);
- }
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), propertyName);
-
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(from, inputData, GraphEdgeLabels.INPUT, props);
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to associate resource {} to property {} in graph. status is {}", componentId, propertyName, operationStatus);
- return Either.right(operationStatus);
- }
-
- return Either.left(createNodeResult.left().value());
-
- }
-
- public TitanOperationStatus addInputToGraph(TitanVertex vertex, String propertyName, InputDefinition inputDefinition, String componentId) {
-
- List<PropertyConstraint> constraints = inputDefinition.getConstraints();
-
- inputDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(componentId, propertyName));
- InputsData inputData = new InputsData(inputDefinition, convertConstraintsToString(constraints));
-
- log.debug("Before adding property to graph {}", inputData);
- Either<TitanVertex, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(inputData);
- if (createNodeResult.isRight()) {
- TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add input {} to graph. status is {}", propertyName, operationStatus);
- return operationStatus;
- }
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), propertyName);
- TitanVertex inputVertex = createNodeResult.left().value();
- TitanOperationStatus createRelResult = titanGenericDao.createEdge(vertex, inputVertex, GraphEdgeLabels.INPUT, props);
- if (!createRelResult.equals(TitanOperationStatus.OK)) {
- TitanOperationStatus operationStatus = createRelResult;
- log.error("Failed to associate resource {} to property {} in graph. status is {}", componentId, propertyName, operationStatus);
- return operationStatus;
- }
-
- return createRelResult;
-
- }
-
- public InputDefinition convertInputDataToInputDefinition(InputsData inputDataResult) {
- if (log.isDebugEnabled())
- log.debug("The object returned after create property is {}", inputDataResult);
-
- InputDefinition propertyDefResult = new InputDefinition(inputDataResult.getPropertyDataDefinition());
- propertyDefResult.setConstraints(convertConstraints(inputDataResult.getConstraints()));
-
- return propertyDefResult;
- }
-
- public boolean isInputExist(List<InputDefinition> inputs, String resourceUid, String inputName) {
-
- if (inputs == null) {
- return false;
- }
-
- for (InputDefinition propertyDefinition : inputs) {
- String parentUniqueId = propertyDefinition.getParentUniqueId();
- String name = propertyDefinition.getName();
-
- if (parentUniqueId.equals(resourceUid) && name.equals(inputName)) {
- return true;
- }
- }
-
- return false;
-
- }
-
- @Override
- public TitanOperationStatus findAllResourceInputs(String uniqueId, List<InputDefinition> inputs) {
- // final NodeElementFetcher<InputDefinition> singleNodeFetcher =
- // (resourceIdParam, attributesParam) ->
- // findNodeNonInheretedInputs(resourceIdParam, componentType,
- // attributesParam);
- // return findAllResourceElementsDefinitionRecursively(uniqueId, inputs,
- // singleNodeFetcher);
- return findNodeNonInheretedInputs(uniqueId, inputs);
- }
-
- @Override
- public TitanOperationStatus findNodeNonInheretedInputs(String uniqueId, List<InputDefinition> inputs) {
- Either<List<ImmutablePair<InputsData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.INPUT, NodeTypeEnum.Input, InputsData.class);
-
- if (childrenNodes.isRight()) {
- TitanOperationStatus status = childrenNodes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.OK;
- }
- return status;
- }
-
- List<ImmutablePair<InputsData, GraphEdge>> values = childrenNodes.left().value();
- if (values != null) {
-
- for (ImmutablePair<InputsData, GraphEdge> immutablePair : values) {
- GraphEdge edge = immutablePair.getValue();
- String inputName = (String) edge.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty());
- log.debug("Input {} is associated to node {}", inputName, uniqueId);
- InputsData inputData = immutablePair.getKey();
- InputDefinition inputDefinition = this.convertInputDataToInputDefinition(inputData);
-
- inputDefinition.setName(inputName);
- inputDefinition.setParentUniqueId(uniqueId);
-
- inputs.add(inputDefinition);
-
- log.trace("findInputsOfNode - input {} associated to node {}", inputDefinition, uniqueId);
- }
-
- }
-
- return TitanOperationStatus.OK;
- }
-
- public Either<InputDefinition, StorageOperationStatus> getInputById(String uniqueId, boolean skipProperties, boolean skipInputsvalue) {
- Either<InputDefinition, TitanOperationStatus> status = getInputFromGraph(uniqueId, skipProperties, skipInputsvalue);
-
- if (status.isRight()) {
- log.error("Failed to get input {} from graph {}. status is {}", uniqueId, status);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value()));
- }
-
- return Either.left(status.left().value());
-
- }
public <ElementDefinition> TitanOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List<ElementDefinition> elements, NodeElementFetcher<ElementDefinition> singleNodeFetcher) {
@@ -580,229 +130,8 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
return TitanOperationStatus.OK;
}
- public TitanOperationStatus associatePropertyToInput(String riId, String inputId, InputValueData property, String name) {
- TitanOperationStatus status = TitanOperationStatus.OK;
- Either<TitanGraph, TitanOperationStatus> graphRes = titanGenericDao.getGraph();
- if (graphRes.isRight()) {
- log.error("Failed to retrieve graph. status is {}", graphRes);
- return graphRes.right().value();
- }
-
- TitanGraph titanGraph = graphRes.left().value();
- @SuppressWarnings("unchecked")
- Iterable<TitanVertex> vertices = titanGraph.query().has(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), property.getUniqueId()).vertices();
- if (vertices == null || false == vertices.iterator().hasNext()) {
- return TitanOperationStatus.INVALID_ID;
- }
- // Either<PropertyData, TitanOperationStatus> findPropertyDefRes =
- // titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property),
- // propertyId, PropertyData.class);
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), name);
- props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), riId);
-
- GraphNode inputData = new UniqueIdData(NodeTypeEnum.Input, inputId);
- GraphNode propertyData = new UniqueIdData(NodeTypeEnum.InputValue, property.getUniqueId());
- Either<GraphRelation, TitanOperationStatus> addPropRefResult = titanGenericDao.createRelation(inputData, propertyData, GraphEdgeLabels.GET_INPUT, props);
-
- if (addPropRefResult.isRight()) {
- status = addPropRefResult.right().value();
- String description = "Failed to associate input " + inputData.getUniqueId() + " to property " + property.getUniqueId() + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ASSOCIATING_INPUT_TO_PROP, description, ErrorSeverity.ERROR);
- return status;
- }
- return status;
-
- }
-
- public TitanOperationStatus associatePropertyToInput(String riId, String inputId, ComponentInstanceProperty property, GetInputValueDataDefinition getInput) {
- TitanOperationStatus status = TitanOperationStatus.OK;
- Either<TitanGraph, TitanOperationStatus> graphRes = titanGenericDao.getGraph();
- if (graphRes.isRight()) {
- log.error("Failed to retrieve graph. status is {}", graphRes);
- return graphRes.right().value();
- }
-
- TitanGraph titanGraph = graphRes.left().value();
- @SuppressWarnings("unchecked")
- Iterable<TitanVertex> vertices = titanGraph.query().has(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), property.getUniqueId()).vertices();
- if (vertices == null || false == vertices.iterator().hasNext()) {
- return TitanOperationStatus.INVALID_ID;
- }
- // Either<PropertyData, TitanOperationStatus> findPropertyDefRes =
- // titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property),
- // propertyId, PropertyData.class);
-
- Map<String, Object> props = new HashMap<String, Object>();
- if(getInput!=null){
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), getInput.getPropName());
- if (getInput.isList()) {
- String index = "";
- if(getInput.getIndexValue()!= null ){
- index = getInput.getIndexValue().toString();
- }else{
- if (getInput.getGetInputIndex() != null) {
- index = getInput.getGetInputIndex().getInputName();
-
- }
- }
- props.put(GraphEdgePropertiesDictionary.GET_INPUT_INDEX.getProperty(), index);
- }
- }
- props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), riId);
-
- GraphNode inputData = new UniqueIdData(NodeTypeEnum.Input, inputId);
- GraphNode propertyData = new UniqueIdData(NodeTypeEnum.PropertyValue, property.getValueUniqueUid());
- Either<GraphRelation, TitanOperationStatus> addPropRefResult = titanGenericDao.createRelation(inputData, propertyData, GraphEdgeLabels.GET_INPUT, props);
-
- if (addPropRefResult.isRight()) {
- status = addPropRefResult.right().value();
- String description = "Failed to associate input " + inputData.getUniqueId() + " to property " + property.getUniqueId() + " in graph. Status is " + status;
- BeEcompErrorManager.getInstance().logInternalFlowError(ASSOCIATING_INPUT_TO_PROP, description, ErrorSeverity.ERROR);
- return status;
- }
- return status;
-
- }
-
- private Either<InputDefinition, TitanOperationStatus> getInputFromGraph(String uniqueId, boolean skipProperties, boolean skipInputsValue) {
-
- Either<InputDefinition, TitanOperationStatus> result = null;
-
- Either<InputsData, TitanOperationStatus> inputRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Input), uniqueId, InputsData.class);
- if (inputRes.isRight()) {
- TitanOperationStatus status = inputRes.right().value();
- log.debug("Failed to retrieve group {} from graph. Status is {}", uniqueId, status);
- BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Group", uniqueId, String.valueOf(status));
- result = Either.right(status);
- return result;
- }
-
- InputsData inputData = inputRes.left().value();
-
- InputDefinition groupDefinition = this.convertInputDataToInputDefinition(inputData);
-
- if (false == skipInputsValue) {
- List<ComponentInstanceInput> propsList = new ArrayList<ComponentInstanceInput>();
-
- Either<List<ImmutablePair<InputValueData, GraphEdge>>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Input), uniqueId, GraphEdgeLabels.GET_INPUT, NodeTypeEnum.InputValue, InputValueData.class);
-
- if (propertyImplNodes.isRight()) {
- TitanOperationStatus status = propertyImplNodes.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- return Either.right(status);
- }
-
- }
- if(propertyImplNodes.isLeft()){
- List<ImmutablePair<InputValueData, GraphEdge>> propertyDataPairList = propertyImplNodes.left().value();
- for (ImmutablePair<InputValueData, GraphEdge> propertyValue : propertyDataPairList) {
-
- InputValueData propertyValueData = propertyValue.getLeft();
- String propertyValueUid = propertyValueData.getUniqueId();
- String value = propertyValueData.getValue();
-
- Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InputValue), propertyValueUid, GraphEdgeLabels.INPUT_IMPL, NodeTypeEnum.Property, PropertyData.class);
- if (propertyDefRes.isRight()) {
- TitanOperationStatus status = propertyDefRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
-
- ImmutablePair<PropertyData, GraphEdge> propertyDefPair = propertyDefRes.left().value();
- String propertyUniqueId = (String) propertyDefPair.left.getUniqueId();
-
- ComponentInstanceInput resourceInstanceProperty = new ComponentInstanceInput();
- // set property original unique id
- resourceInstanceProperty.setUniqueId(propertyUniqueId);
- // set resource id
- // TODO: esofer add resource id
- resourceInstanceProperty.setParentUniqueId(null);
- // set value
- resourceInstanceProperty.setValue(value);
- // set property value unique id
- resourceInstanceProperty.setValueUniqueUid(propertyValueUid);
- // set rules
- // resourceInstanceProperty.setRules(propertyValueData.getRules());
-
- propsList.add(resourceInstanceProperty);
-
- }
-
- groupDefinition.setInputs(propsList);
- }
-
- }
-
- if (false == skipProperties) {
- Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.GET_INPUT, NodeTypeEnum.PropertyValue, PropertyValueData.class);
-
- if (propertyImplNodes.isRight()) {
- TitanOperationStatus status = propertyImplNodes.right().value();
- return Either.right(status);
- }
-
- List<ImmutablePair<PropertyValueData, GraphEdge>> list = propertyImplNodes.left().value();
-
- if (list == null || true == list.isEmpty()) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- List<ComponentInstanceProperty> propsRresult = new ArrayList<>();
- for (ImmutablePair<PropertyValueData, GraphEdge> propertyValueDataPair : list) {
- PropertyValueData propertyValueData = propertyValueDataPair.left;
- String propertyValueUid = propertyValueData.getUniqueId();
- String value = propertyValueData.getValue();
-
- Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class);
- if (propertyDefRes.isRight()) {
- TitanOperationStatus status = propertyDefRes.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- return Either.right(status);
- }
-
- }
- if(propertyDefRes.isLeft()){
-
- ImmutablePair<PropertyData, GraphEdge> propertyDefPair = propertyDefRes.left().value();
- PropertyData propertyData = propertyDefPair.left;
- String propertyUniqueId = (String) propertyData.getPropertyDataDefinition().getUniqueId();
-
- ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty();
- // set property original unique id
- resourceInstanceProperty.setUniqueId(propertyUniqueId);
- // set resource id
- // TODO: esofer add resource id
- resourceInstanceProperty.setParentUniqueId(null);
- // set value
- resourceInstanceProperty.setValue(value);
- // set property value unique id
- resourceInstanceProperty.setValueUniqueUid(propertyValueData.getUniqueId());
- // set rules
- resourceInstanceProperty.setRules(propertyValueData.getRules());
- resourceInstanceProperty.setType(propertyData.getPropertyDataDefinition().getType());
- resourceInstanceProperty.setSchema(propertyData.getPropertyDataDefinition().getSchema());
- resourceInstanceProperty.setName((String) propertyValueDataPair.right.getProperties().get(GraphPropertiesDictionary.NAME.getProperty()));
-
- propsRresult.add(resourceInstanceProperty);
- }
-
- groupDefinition.setProperties(propsRresult);
- }
-
- }
-
- result = Either.left(groupDefinition);
-
- return result;
-
- }
+ @Override
public ImmutablePair<TitanOperationStatus, String> findInputValue(String resourceInstanceId, String propertyId) {
log.debug("Going to check whether the property {} already added to resource instance {}", propertyId, resourceInstanceId);
@@ -842,40 +171,6 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
}
- /**
- * return all properties associated to resource instance. The result does contains the property unique id but not its type, default value...
- *
- * @param resourceInstanceUid
- * @return
- */
- public Either<List<ComponentInstanceInput>, StorageOperationStatus> getComponentInstanceInputsByInputId(String resourceInstanceUid, String inputId) {
-
- Either<List<ComponentInstanceInput>, TitanOperationStatus> status = getComponentInstanceInputsByInputId(inputId);
- if (status.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value()));
- }
-
- return Either.left(status.left().value());
-
- }
-
- /**
- * return all properties associated to resource instance. The result does contains the property unique id but not its type, default value...
- *
- * @param resourceInstanceUid
- * @return
- */
- public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstancePropertiesByInputId(String resourceInstanceUid, String inputId) {
-
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> status = getComponentInstancePropertiesByInputId(inputId);
- if (status.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value()));
- }
-
- return Either.left(status.left().value());
-
- }
-
public Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllInputsOfResourceInstanceOnlyInputDefId(String resourceInstanceUid, NodeTypeEnum instanceNodeType) {
Either<ComponentInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, ComponentInstanceData.class);
@@ -967,231 +262,7 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
return Either.left(result);
}
- public Either<List<ComponentInstanceInput>, TitanOperationStatus> getComponentInstanceInputsByInputId(String inputId) {
-
- Either<InputsData, TitanOperationStatus> findResInputRes = titanGenericDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId, InputsData.class);
-
- if (findResInputRes.isRight()) {
- TitanOperationStatus status = findResInputRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
-
-
-
- // Either<List<InputValueData>, TitanOperationStatus> propertyImplNodes
- // = titanGenericDao.getByCriteria(NodeTypeEnum.InputValue, props,
- // InputValueData.class);
- Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId);
-
- if (vertexService.isRight()) {
- log.debug("failed to fetch vertex of resource input for id = {}", inputId);
- TitanOperationStatus status = vertexService.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
-
- return Either.right(status);
- }
- TitanVertex vertex = vertexService.left().value();
-
- Either<List<ImmutablePair<InputValueData, GraphEdge>>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId, GraphEdgeLabels.GET_INPUT, NodeTypeEnum.InputValue, InputValueData.class);
-
- //////////////////////////////////////////////////////////////////////////////////////////////////////////////
-
- if (propertyImplNodes.isRight()) {
- TitanOperationStatus status = propertyImplNodes.right().value();
- return Either.right(status);
- }
-
- List<ImmutablePair<InputValueData, GraphEdge>> list = propertyImplNodes.left().value();
-
- if (list == null || true == list.isEmpty()) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- List<ComponentInstanceInput> result = new ArrayList<>();
- for (ImmutablePair<InputValueData, GraphEdge> propertyValueDataPair : list) {
- InputValueData propertyValueData = propertyValueDataPair.left;
- String propertyValueUid = propertyValueData.getUniqueId();
- String value = propertyValueData.getValue();
- // Either<List<Edge>, TitanOperationStatus> out =
- // titanGenericDao.getEdgesForNode(propertyValueData,
- // Direction.OUT);
- // Either<List<Edge>, TitanOperationStatus> in =
- // titanGenericDao.getEdgesForNode(propertyValueData, Direction.IN);
- Either<Edge, TitanOperationStatus> inputsvalueEges = titanGenericDao.getIncomingEdgeByCriteria(propertyValueData, GraphEdgeLabels.INPUT_VALUE, null);
- if (inputsvalueEges.isRight()) {
- TitanOperationStatus status = inputsvalueEges.right().value();
-
- return Either.right(status);
- }
- Edge edge = inputsvalueEges.left().value();
- String componentInsName = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.NAME.getProperty());
- String componentInsId = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
-
- Either<ImmutablePair<InputsData, GraphEdge>, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InputValue), propertyValueUid, GraphEdgeLabels.INPUT_IMPL, NodeTypeEnum.Input, InputsData.class);
-
- if (propertyDefRes.isRight()) {
- TitanOperationStatus status = propertyDefRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
-
- ImmutablePair<InputsData, GraphEdge> propertyDefPair = propertyDefRes.left().value();
-
- InputsData propertyData = propertyDefPair.left;
-
- Either<Edge, TitanOperationStatus> inputsEges = titanGenericDao.getIncomingEdgeByCriteria(propertyData, GraphEdgeLabels.INPUT, null);
- if (inputsEges.isRight()) {
- TitanOperationStatus status = inputsEges.right().value();
-
- return Either.right(status);
- }
- edge = inputsEges.left().value();
- String inputName = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.NAME.getProperty());
-
- String propertyUniqueId = (String) propertyData.getPropertyDataDefinition().getUniqueId();
-
- ComponentInstanceInput resourceInstanceProperty = new ComponentInstanceInput(propertyData.getPropertyDataDefinition(), inputId, value, propertyValueUid);
- // set property original unique id
- resourceInstanceProperty.setUniqueId(propertyUniqueId);
- resourceInstanceProperty.setName(inputName);
- // set resource id
- // TODO: esofer add resource id
- resourceInstanceProperty.setParentUniqueId(null);
- // set value
- resourceInstanceProperty.setValue(value);
- // set property value unique id
- resourceInstanceProperty.setValueUniqueUid(propertyValueData.getUniqueId());
- // set rules
- // resourceInstanceProperty.setRules(propertyValueData.getRules());
- resourceInstanceProperty.setType(propertyData.getPropertyDataDefinition().getType());
- resourceInstanceProperty.setSchema(propertyData.getPropertyDataDefinition().getSchema());
- resourceInstanceProperty.setComponentInstanceName(componentInsName);
- resourceInstanceProperty.setComponentInstanceId(componentInsId);
-
- result.add(resourceInstanceProperty);
- }
-
- return Either.left(result);
-
- }
-
- public Either<List<ComponentInstanceProperty>, TitanOperationStatus> getComponentInstancePropertiesByInputId(String inputId) {
-
- Either<InputsData, TitanOperationStatus> findResInputRes = titanGenericDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId, InputsData.class);
-
- if (findResInputRes.isRight()) {
- TitanOperationStatus status = findResInputRes.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- return Either.right(status);
- }
-
- //Map<String, Object> props = new HashMap<String, Object>();
- //props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), resourceInstanceUid);
-
- // Either<List<PropertyValueData>, TitanOperationStatus>
- // propertyImplNodes =
- // titanGenericDao.getByCriteria(NodeTypeEnum.PropertyValue, props,
- // PropertyValueData.class);
- Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId);
-
- if (vertexService.isRight()) {
- log.debug("failed to fetch vertex of resource input for id = {}", inputId);
- TitanOperationStatus status = vertexService.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
-
- return Either.right(status);
- }
- TitanVertex vertex = vertexService.left().value();
-
- // Either<List<ImmutablePair<PropertyValueData, GraphEdge>>,
- // TitanOperationStatus> propertyImplNodes =
- // titanGenericDao.getChildrenByEdgeCriteria(vertex, inputId,
- // GraphEdgeLabels.GET_INPUT, NodeTypeEnum.PropertyValue,
- // PropertyValueData.class, props);
- Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId, GraphEdgeLabels.GET_INPUT, NodeTypeEnum.PropertyValue, PropertyValueData.class);
-
- if (propertyImplNodes.isRight()) {
- TitanOperationStatus status = propertyImplNodes.right().value();
- return Either.right(status);
- }
-
- List<ImmutablePair<PropertyValueData, GraphEdge>> list = propertyImplNodes.left().value();
-
- if (list == null || true == list.isEmpty()) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- List<ComponentInstanceProperty> result = new ArrayList<>();
- for (ImmutablePair<PropertyValueData, GraphEdge> propertyValueDataPair : list) {
- PropertyValueData propertyValueData = propertyValueDataPair.left;
- String propertyValueUid = propertyValueData.getUniqueId();
- String value = propertyValueData.getValue();
-
- String componentInstanceId = (String) propertyValueDataPair.right.getProperties().get(GraphEdgePropertiesDictionary.OWNER_ID.getProperty());
-
- Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class);
- if (propertyDefRes.isRight()) {
- TitanOperationStatus status = propertyDefRes.right().value();
- return Either.right(status);
- }
-
- ImmutablePair<PropertyData, GraphEdge> propertyDefPair = propertyDefRes.left().value();
- PropertyData propertyData = propertyDefPair.left;
- String propertyUniqueId = (String) propertyData.getPropertyDataDefinition().getUniqueId();
-
- Either<TitanVertex, TitanOperationStatus> originVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), propertyUniqueId);
- if (originVertexEither.isRight()) {
- log.debug("Failed to fetch vertex of property for id {} error {}", propertyUniqueId, originVertexEither.right().value());
- return Either.right(originVertexEither.right().value());
- }
- TitanVertex originVertex = originVertexEither.left().value();
- Iterator<Edge> edgeIter = originVertex.edges(Direction.IN, GraphEdgeLabels.PROPERTY.getProperty());
- if (edgeIter == null) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- String propertyName = "";
-
- while (edgeIter.hasNext()) {
- TitanEdge edge = (TitanEdge) edgeIter.next();
- propertyName = (String) edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value();
- }
-
- ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty();
- // set property original unique id
- resourceInstanceProperty.setUniqueId(propertyUniqueId);
- // set resource id
- // TODO: esofer add resource id
- resourceInstanceProperty.setParentUniqueId(null);
- // set value
- resourceInstanceProperty.setValue(value);
- // set property value unique id
- resourceInstanceProperty.setValueUniqueUid(propertyValueData.getUniqueId());
- // set rules
- resourceInstanceProperty.setRules(propertyValueData.getRules());
- resourceInstanceProperty.setType(propertyData.getPropertyDataDefinition().getType());
- resourceInstanceProperty.setSchema(propertyData.getPropertyDataDefinition().getSchema());
- resourceInstanceProperty.setName(propertyName);
- resourceInstanceProperty.setComponentInstanceId(componentInstanceId);
-
-
- result.add(resourceInstanceProperty);
- }
-
- return Either.left(result);
- }
-
+ @Override
public ComponentInstanceInput buildResourceInstanceInput(InputValueData propertyValueData, ComponentInstanceInput resourceInstanceInput) {
String value = propertyValueData.getValue();
@@ -1202,271 +273,5 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati
return instanceProperty;
}
- public Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllInputsOfResourceInstance(ComponentInstance compInstance) {
-
- Either<List<ComponentInstanceInput>, TitanOperationStatus> result;
-
- return getAllInputsOfResourceInstanceOnlyInputDefId(compInstance.getUniqueId());
-
- }
-
-
-
- private Either<List<InputDefinition>, StorageOperationStatus> createInputsFromProperty(String resourceId, NodeTypeEnum nodeType, Map<String, DataTypeDefinition> dataTypes, List<InputDefinition> resList, Map<String, List<ComponentInstancePropInput>> newInputsPropsMap) {
- for (Entry<String, List<ComponentInstancePropInput>> entry : newInputsPropsMap.entrySet()) {
- String compInstId = entry.getKey();
- List<ComponentInstancePropInput> properties = entry.getValue();
-
- Either<TitanVertex, TitanOperationStatus> ciVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), compInstId);
- if (ciVertexEither.isRight()) {
- log.debug("Failed to fetch vertex of resource instance for id {} error {}", compInstId, ciVertexEither.right().value());
- return Either.right( DaoStatusConverter.convertTitanStatusToStorageStatus(ciVertexEither.right().value()));
- }
- TitanVertex ciVertex = ciVertexEither.left().value();
-
-
- //String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty());
- String compInstname = (String) titanGenericDao.getProperty(ciVertex, GraphPropertiesDictionary.NORMALIZED_NAME.getProperty());
- String inputName = compInstname;
-
- if (properties != null && !properties.isEmpty()) {
- for (ComponentInstancePropInput propInput : properties) {
- Either<InputDefinition, StorageOperationStatus> createInputRes = createInputForComponentInstance(resourceId, nodeType, dataTypes, compInstId, inputName, propInput);
-
- if (createInputRes.isRight()) {
- log.debug("Failed to create input of resource instance for id {} error {}", compInstId, createInputRes.right().value());
- return Either.right(createInputRes.right().value());
- }
-
- resList.add(createInputRes.left().value());
-
- }
- }
-
- }
- return Either.left(resList);
- }
-
- private Either<InputDefinition, StorageOperationStatus> createInputForComponentInstance(String resourceId, NodeTypeEnum nodeType, Map<String, DataTypeDefinition> dataTypes, String compInstId, String inputName, ComponentInstancePropInput propInput) {
- String propertiesName = propInput.getPropertiesName() ;
- PropertyDefinition selectedProp = propInput.getInput();
- String[] parsedPropNames = propInput.getParsedPropNames();
- if(parsedPropNames != null){
- for(String str: parsedPropNames){
- inputName += "_" + str;
- }
- } else {
- inputName += "_" + propInput.getName();
- }
-
- InputDefinition input = null;
- ComponentInstanceProperty prop = propInput;
-
- if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){
- input = new InputDefinition(selectedProp);
- }else{
- input = new InputDefinition(prop);
- input.setName(inputName + "_" + prop.getName());
-
- }
- input.setName(inputName);
-
- JSONObject jobject = new JSONObject();
-
-
- if(prop.getValueUniqueUid() == null || prop.getValueUniqueUid().isEmpty()){
- if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){
-
- jobject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jobject, inputName);
- prop.setValue(jobject.toJSONString());
-
- }else{
-
- jobject.put(GET_INPUT, input.getName());
- prop.setValue(jobject.toJSONString());
-
-
- }
- Either<Integer, StorageOperationStatus> increaseCounterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(compInstId, GraphPropertiesDictionary.PROPERTY_COUNTER, true);
- if (increaseCounterRes.isRight()) {
- log.debug("Failed to increase resource property counter {} to resource instance {}", prop, compInstId);
-
- return Either.right( increaseCounterRes.right().value());
- }
- Integer index = increaseCounterRes.left().value();
- Either<ComponentInstanceProperty, StorageOperationStatus> result = componentInstanceOperation.addPropertyValueToResourceInstance(prop, compInstId, false, index, true);
- if (result.isRight()) {
- log.debug("Failed to add property value {} to resource instance {}", prop, compInstId);
- return Either.right( result.right().value());
- }
- prop = result.left().value();
-
- }else{
-
- String value = prop.getValue();
- if(value != null){
- Object objValue = new Yaml().load(value);
- if( objValue instanceof Map || objValue instanceof List ){
- if(propertiesName == null ||propertiesName.isEmpty()){
- jobject.put(GET_INPUT, input.getName());
- prop.setValue(jobject.toJSONString());
- prop.setRules(null);
-
- }else{
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue;
- createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName);
- Gson gson = new Gson();
- String json = gson.toJson(mappedToscaTemplate);
- prop.setValue(json);
- prop.setRules(null);
- }
-
- }else{
- jobject.put(GET_INPUT, input.getName());
- prop.setValue(jobject.toJSONString());
- prop.setRules(null);
- }
- }else{
- jobject.put(GET_INPUT, input.getName());
- prop.setValue(jobject.toJSONString());
- prop.setRules(null);
- }
-
- Either<PropertyValueData, TitanOperationStatus> eitherStatus = componentInstanceOperation.updatePropertyOfResourceInstance(prop, compInstId, false);
-
- if (eitherStatus.isRight()) {
- log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", prop, compInstId, eitherStatus.right().value().name());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value()));
-
- } else {
- PropertyValueData propertyValueData = eitherStatus.left().value();
-
- prop = propertyOperation.buildResourceInstanceProperty(propertyValueData, prop);
-
- log.debug("The returned ResourceInstanceProperty is {}", prop);
-
- Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(prop.getPath(), propertyValueData.getUniqueId(), prop.getDefaultValue());
- if (findDefaultValue.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value()));
-
- }
- String defaultValue = findDefaultValue.left().value();
- prop.setDefaultValue(defaultValue);
- log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue);
-
- prop.setComponentInstanceId(compInstId);
-
-
-
- }
-
-
- }
-
- StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(input, dataTypes);
- if (validateAndUpdateProperty != StorageOperationStatus.OK) {
- log.error("Property {} is invalid. Status is {}", input, validateAndUpdateProperty);
- return Either.right(validateAndUpdateProperty);
- }
-
- Either<InputsData, TitanOperationStatus> addPropertyToGraph = addInputToGraph(input.getName(), input, resourceId, nodeType);
-
- if (addPropertyToGraph.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyToGraph.right().value()));
- }
- InputDefinition createdInputyDefinition = convertInputDataToInputDefinition(addPropertyToGraph.left().value());
- createdInputyDefinition.setName(input.getName());
- createdInputyDefinition.setParentUniqueId(resourceId);
-
- TitanOperationStatus status = associatePropertyToInput(compInstId, createdInputyDefinition.getUniqueId(), prop, null);
- if (status != TitanOperationStatus.OK) {
- log.debug("Failed to associate input {} tp property value{} ", createdInputyDefinition.getName(), prop.getValueUniqueUid());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
-
- return Either.left(createdInputyDefinition);
-
- }
-
- private JSONObject createJSONValueForProperty (int i, String [] parsedPropNames, JSONObject ooj, String inputName){
-
- while(i >= 1){
- if( i == parsedPropNames.length -1){
- JSONObject jobProp = new JSONObject();
- jobProp.put(GET_INPUT, inputName);
- ooj.put(parsedPropNames[i], jobProp);
- i--;
- return createJSONValueForProperty (i, parsedPropNames, ooj, inputName);
- }else{
- JSONObject res = new JSONObject();
- res.put(parsedPropNames[i], ooj);
- i --;
- res = createJSONValueForProperty (i, parsedPropNames, res, inputName);
- return res;
- }
- }
-
- return ooj;
- }
-
- public void resetInputName(Map<String, Object> lhm1, String inputName){
- for (Map.Entry<String, Object> entry : lhm1.entrySet()) {
- String key = entry.getKey();
- Object value = entry.getValue();
- if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) {
- value = "";
- lhm1.remove(key);
- } else if (value instanceof Map) {
- Map<String, Object> subMap = (Map<String, Object>)value;
- resetInputName(subMap, inputName);
- } else {
- continue;
- }
-
- }
- }
-
- private Map<String, Object> createInputValue(Map<String, Object> lhm1, int index, String[] inputNames, String inputName){
- while(index < inputNames.length){
- if(lhm1.containsKey(inputNames[index])){
- Object value = lhm1.get(inputNames[index]);
- if (value instanceof Map){
- if(index == inputNames.length -1){
- ((Map) value).put(GET_INPUT, inputName);
- return ((Map) value);
-
- }else{
- index++;
- return createInputValue((Map)value, index, inputNames, inputName);
- }
- }else{
- Map<String, Object> jobProp = new HashMap<>();
- if(index == inputNames.length -1){
- jobProp.put(GET_INPUT, inputName);
- lhm1.put(inputNames[index], jobProp);
- return lhm1;
- }else{
- lhm1.put(inputNames[index], jobProp);
- index++;
- return createInputValue(jobProp, index, inputNames, inputName);
- }
- }
- }else{
- Map<String, Object> jobProp = new HashMap<>();
- lhm1.put(inputNames[index], jobProp);
- if(index == inputNames.length -1){
- jobProp.put(GET_INPUT, inputName);
- return jobProp;
- }else{
- index++;
- return createInputValue(jobProp, index, inputNames, inputName);
- }
- }
- }
- return lhm1;
- }
-
-
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java
index a7c883b14e..1c03d579a0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java
@@ -71,12 +71,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
private TitanGenericDao titanGenericDao;
@Override
- public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName) {
-
- return addInterfaceToResource(interf, resourceId, interfaceName, false);
- }
-
- @Override
public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean inTransaction) {
return createInterfaceOnResource(interf, resourceId, interfaceName, true, inTransaction);
@@ -113,34 +107,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
- private Either<TitanVertex, TitanOperationStatus> addOperationToGraph(InterfaceDefinition interf, String opName, Operation op, TitanVertex interfaceVertex) {
-
- String interfaceId = (String) titanGenericDao.getProperty(interfaceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- op.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(interfaceId, opName));
- OperationData operationData = new OperationData(op);
-
- log.debug("Before adding operation to graph {}", operationData);
- Either<TitanVertex, TitanOperationStatus> createOpNodeResult = titanGenericDao.createNode(operationData);
-
- if (createOpNodeResult.isRight()) {
- TitanOperationStatus opStatus = createOpNodeResult.right().value();
- log.error("Failed to add operation {} to graph. status is {}", opName, opStatus);
- return Either.right(opStatus);
- }
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), opName);
- TitanVertex operationVertex = createOpNodeResult.left().value();
- TitanOperationStatus createRelResult = titanGenericDao.createEdge(interfaceVertex, operationVertex, GraphEdgeLabels.INTERFACE_OPERATION, props);
-
- if (!createRelResult.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate operation {} to property {} in graph. status is {}", interfaceId, opName, createRelResult);
-
- return Either.right(createRelResult);
- }
- return Either.left(operationVertex);
- }
-
private InterfaceDefinition convertInterfaceDataToInterfaceDefinition(InterfaceData interfaceData) {
log.debug("The object returned after create interface is {}", interfaceData);
@@ -183,25 +149,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
}
- private Either<TitanVertex, TitanOperationStatus> addInterfaceToGraph(InterfaceDefinition interfaceInfo, String interfaceName, String resourceId, TitanVertex metadataVertex) {
-
- InterfaceData interfaceData = new InterfaceData(interfaceInfo);
-
- String interfaceNameSplitted = getShortInterfaceName(interfaceInfo);
-
- interfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted));
-
- Either<TitanVertex, TitanOperationStatus> existInterface = titanGenericDao.getVertexByProperty(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId());
-
- if (existInterface.isRight()) {
-
- return createInterfaceNodeAndRelation(interfaceNameSplitted, resourceId, interfaceData, metadataVertex);
- } else {
- log.debug("Interface {} already exist", interfaceData.getUniqueId());
- return Either.right(TitanOperationStatus.ALREADY_EXIST);
- }
- }
-
private Either<InterfaceData, TitanOperationStatus> createInterfaceNodeAndRelation(String interfaceName, String resourceId, InterfaceData interfaceData, ResourceMetadataData resourceData) {
log.debug("Before adding interface to graph {}", interfaceData);
Either<InterfaceData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData, InterfaceData.class);
@@ -804,70 +751,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
@Override
- public StorageOperationStatus createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction, TitanVertex metadataVertex) {
-
- Either<TitanVertex, TitanOperationStatus> interfaceResult = addInterfaceToGraph(interf, interfaceName, resourceId, metadataVertex);
-
- if (interfaceResult.isRight()) {
- if (false == inTransaction) {
- titanGenericDao.rollback();
- }
- log.error("Failed to add interface {} to resource {}", interfaceName, resourceId);
- return DaoStatusConverter.convertTitanStatusToStorageStatus(interfaceResult.right().value());
- } else {
-
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- TitanVertex interfaceVertex = interfaceResult.left().value();
-
- // InterfaceDefinition interfaceDefResult =
- // convertInterfaceDataToInterfaceDefinition(interfaceData);
- Map<String, Operation> operations = interf.getOperationsMap();
- if (operations != null && !operations.isEmpty()) {
- Set<String> opNames = operations.keySet();
- for (String operationName : opNames) {
-
- Operation op = operations.get(operationName);
- Either<TitanVertex, TitanOperationStatus> operationResult = addOperationToGraph(interf, operationName, op, interfaceVertex);
- if (operationResult.isRight()) {
- if (false == inTransaction) {
- titanGenericDao.rollback();
- }
- log.error("Failed to add operation {} to interface {}", operationName, interfaceName);
- return DaoStatusConverter.convertTitanStatusToStorageStatus(operationResult.right().value());
- } else {
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- TitanVertex operationVertex = operationResult.left().value();
-
- ArtifactDefinition art = op.getImplementationArtifact();
- if (art != null) {
- String opId = (String) titanGenericDao.getProperty(operationVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
- StorageOperationStatus artRes = artifactOperation.addArifactToComponent(art, opId, NodeTypeEnum.InterfaceOperation, failIfExist, operationVertex);
- if (!artRes.equals(StorageOperationStatus.OK)) {
- if (false == inTransaction) {
- titanGenericDao.rollback();
- }
- log.error("Failed to add artifact {} to interface {}", operationName, interfaceName);
- return artRes;
- }
- }
- }
- }
- }
- return StorageOperationStatus.OK;
- }
-
- }
-
- @Override
- public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationId) {
- return deleteInterfaceOperation(resourceId, interfaceName, operationId, false);
- }
-
- @Override
public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationId, boolean inTransaction) {
Either<Operation, TitanOperationStatus> status = removeOperationOnGraph(resourceId, interfaceName, operationId);
@@ -889,29 +772,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
- @Override
- public Either<InterfaceDefinition, StorageOperationStatus> deleteInterfaceOfResourceOnGraph(String resourceId, InterfaceDefinition interfaceDef, boolean inTransaction) {
-
- Map<String, Operation> operations = interfaceDef.getOperationsMap();
- String interfaceNameSplitted = getShortInterfaceName(interfaceDef);
- if (operations != null) {
- for (Entry<String, Operation> entry : operations.entrySet()) {
-
- Operation op = entry.getValue();
- Either<Operation, StorageOperationStatus> removeOperationFromResource = deleteInterfaceOperation(resourceId, interfaceNameSplitted, op.getUniqueId(), true);
- if (removeOperationFromResource.isRight()) {
- if (false == inTransaction) {
- titanGenericDao.rollback();
- }
- log.error("Failed to delete operation {} of interface {} resource {}", op.getUniqueId(), interfaceDef.getType(), resourceId);
- return Either.right(removeOperationFromResource.right().value());
- }
- }
- }
- return Either.left(interfaceDef);
-
- }
-
private Either<Operation, TitanOperationStatus> removeOperationOnGraph(String resourceId, String interfaceName, String operationId) {
log.debug("Before deleting operation from graph {}", operationId);
@@ -1091,27 +951,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
}
}
- @Override
- public StorageOperationStatus associateInterfaceToNode(GraphNode node, InterfaceDefinition interfaceDefinition, TitanVertex metadataVertex) {
-
- Either<TitanVertex, TitanOperationStatus> interfaceData = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDefinition.getUniqueId());
- if (interfaceData.isRight()) {
- return DaoStatusConverter.convertTitanStatusToStorageStatus(interfaceData.right().value());
- }
-
- Map<String, Object> properties = new HashMap<String, Object>();
-
- String interfaceName = getShortInterfaceName(interfaceDefinition);
-
- properties.put(GraphPropertiesDictionary.NAME.getProperty(), interfaceName.toLowerCase());
- TitanOperationStatus createRelation = titanGenericDao.createEdge(metadataVertex, interfaceData.left().value(), GraphEdgeLabels.INTERFACE, properties);
- if (!createRelation.equals(TitanOperationStatus.OK)) {
- return DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation);
- }
-
- return StorageOperationStatus.OK;
- }
-
public String getShortInterfaceName(InterfaceDataDefinition interfaceDefinition) {
String[] packageName = interfaceDefinition.getType().split("\\.");
String interfaceName;
@@ -1130,41 +969,4 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation
return createInterfaceType(interf, false);
}
- @Override
- public Either<Operation, StorageOperationStatus> getSpecificOperation(String resourceId, String interfaceType, String operationName) {
- log.trace("Getting operation, resourceId {}, interfaceType {}, operationName {}", resourceId, interfaceType, operationName);
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = getAllInterfacesOfResource(resourceId, false);
- if (allInterfacesOfResource.isRight() || allInterfacesOfResource.left().value() == null || allInterfacesOfResource.left().value().get(interfaceType) == null) {
- log.debug("Couldn't find interface definition of type {} for resource id {}", interfaceType, resourceId);
- return Either.right(allInterfacesOfResource.right().value());
- }
- InterfaceDefinition interfaceDefinition = allInterfacesOfResource.left().value().get(interfaceType);
- Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
- if (operations == null || operations.get(operationName) == null) {
- log.debug("Couldn't find operation for operation name {}, interface type {}", operationName, interfaceType);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- return Either.left(operations.get(operationName));
- }
-
- @Override
- public Either<InterfaceDefinition, StorageOperationStatus> dissociateInterfaceFromNode(GraphNode node, InterfaceDefinition interfaceDefinition) {
-
- Either<InterfaceData, TitanOperationStatus> interfaceData = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDefinition.getUniqueId(), InterfaceData.class);
- if (interfaceData.isRight()) {
- log.debug("Couldn't find interface {}", interfaceDefinition);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(interfaceData.right().value()));
- }
-
- InterfaceData value = interfaceData.left().value();
- Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(node, value, GraphEdgeLabels.INTERFACE);
- if (deleteRelation.isRight()) {
- TitanOperationStatus status = deleteRelation.right().value();
- log.debug("Couldn't dissociate interface between node {} to node {}. Status is {}", node.getUniqueId(), value.getUniqueId(), status);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
-
- return Either.left(interfaceDefinition);
- }
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java
deleted file mode 100644
index 2537891bbd..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java
+++ /dev/null
@@ -1,1077 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
-import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.ILifecycleOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
-import org.openecomp.sdc.be.resources.data.UniqueIdData;
-import org.openecomp.sdc.be.resources.data.UserData;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import fj.data.Either;
-
-@org.springframework.stereotype.Component("lifecycle-operation")
-public class LifecycleOperation implements ILifecycleOperation {
-
- public static final String VERSION_DELIMETER = ".";
- public static final String VERSION_DELIMETER_REGEXP = "\\.";
-
- public LifecycleOperation() {
- super();
- }
-
- private static Logger log = LoggerFactory.getLogger(LifecycleOperation.class.getName());
-
- @javax.annotation.Resource
- private ResourceOperation resourceOperation;
-
- @javax.annotation.Resource
- private ServiceOperation serviceOperation;
-
- @javax.annotation.Resource
- private ProductOperation productOperation;
-
- @javax.annotation.Resource
- private TitanGenericDao titanGenericDao;
-
- public ResourceOperation getResourceOperation() {
- return resourceOperation;
- }
-
- public void setResourceOperation(ResourceOperation resourceOperation) {
- this.resourceOperation = resourceOperation;
- }
-
- public ServiceOperation getServiceOperation() {
- return serviceOperation;
- }
-
- public ComponentOperation getComponentOperation(NodeTypeEnum componentType) {
- if (NodeTypeEnum.Service.equals(componentType)) {
- return serviceOperation;
- } else if (NodeTypeEnum.Resource.equals(componentType)) {
- return resourceOperation;
- } else if (NodeTypeEnum.Product.equals(componentType)) {
- return productOperation;
- }
- return null;
- }
-
- public void setServiceOperation(ServiceOperation serviceOperation) {
- this.serviceOperation = serviceOperation;
- }
-
- public TitanGenericDao getTitanGenericDao() {
- return titanGenericDao;
- }
-
- public void setTitanGenericDao(TitanGenericDao titanGenericDao) {
- this.titanGenericDao = titanGenericDao;
- }
-
- @Override
- public Either<User, StorageOperationStatus> getComponentOwner(String resourceId, NodeTypeEnum nodeType, boolean inTransaction) {
-
- Either<User, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR);
- try {
-
- Either<ImmutablePair<UserData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.STATE, NodeTypeEnum.User, UserData.class);
-
- if (parentNode.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentNode.right().value()));
- }
-
- ImmutablePair<UserData, GraphEdge> value = parentNode.left().value();
-
- User owner = new User(value.left);
- result = Either.left(owner);
-
- } finally {
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- }
- return result;
- }
-
- @Override
- public Either<? extends Component, StorageOperationStatus> checkoutComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction) {
- Either<? extends Component, StorageOperationStatus> result = null;
-
- try {
- // update old component
- if (!component.getLifecycleState().equals(LifecycleStateEnum.CERTIFIED)) {
- component.setHighestVersion(false);
- ComponentOperation componentOperation = getComponentOperation(nodeType);
- Either<? extends Component, StorageOperationStatus> updateComponent = componentOperation.updateComponent(component, inTransaction, titanGenericDao, component.getClass(), nodeType);
- if (updateComponent.isRight()) {
- StorageOperationStatus error = updateComponent.right().value();
- log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, error);
- return Either.right(error);
- }
-
- StorageOperationStatus changeStateToLastState = changeStateRelation(nodeType, component.getUniqueId(), currentOwner, GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE);
- if (!changeStateToLastState.equals(StorageOperationStatus.OK)) {
- result = Either.right(changeStateToLastState);
- return result;
- }
- }
-
- // clone the component
- result = cloneComponentForCheckout(component, nodeType, modifier);
- if (result.isRight()) {
- log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, result.right().value());
- return result;
- }
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- return result;
- }
-
- private Either<? extends Component, StorageOperationStatus> cloneComponentForCertified(Component component, User modifier, Integer majorVersion) {
-
- // set new version
- String certifiedVersion = (majorVersion + 1) + VERSION_DELIMETER + "0";
- component.setVersion(certifiedVersion);
- component.setLifecycleState(LifecycleStateEnum.CERTIFIED);
- component.setLastUpdateDate(null);
- component.setLastUpdaterUserId(modifier.getUserId());
- component.setHighestVersion(true);
-
- ComponentOperation componentOperation = getComponentOperation(component.getComponentType().getNodeType());
- Either<? extends Component, StorageOperationStatus> cloneComponentResult = componentOperation.cloneComponent(component, certifiedVersion, LifecycleStateEnum.CERTIFIED, true);
-
- return cloneComponentResult;
- }
-
- @Override
- public Either<? extends Component, StorageOperationStatus> undoCheckout(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction) {
- Either<? extends Component, StorageOperationStatus> result = null;
- ComponentOperation componentOperation = getComponentOperation(nodeType);
-
- // this is in case prevVersion is 0.0 - returning OOTB component
- Component prevComponent = componentOperation.getDefaultComponent();
- try {
- // find previous version
- String[] versionParts = component.getVersion().split(VERSION_DELIMETER_REGEXP);
- Integer minorVersion = Integer.parseInt(versionParts[1]) - 1;
- String previousVersion = versionParts[0] + VERSION_DELIMETER + minorVersion;
-
- if (!previousVersion.equals("0.0")) {
- Either<? extends Component, StorageOperationStatus> updateOldResourceResult = updateOldComponentBeforeUndoCheckout(componentOperation, prevComponent, component, previousVersion, nodeType, true);
- if (updateOldResourceResult.isRight()) {
- result = updateOldResourceResult;
- return result;
- }
- prevComponent = updateOldResourceResult.left().value();
- }
-
- // delete the component
- Either<? extends Component, StorageOperationStatus> deleteResourceResult = componentOperation.deleteComponent(component.getUniqueId(), true);
- if (deleteResourceResult.isRight()) {
- result = deleteResourceResult;
- return result;
- }
-
- // return the deleted resource
- result = Either.left(prevComponent);
-
- return result;
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public Either<? extends Component, StorageOperationStatus> checkinComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction) {
- Either<? extends Component, StorageOperationStatus> result = null;
- try {
- StorageOperationStatus updateCheckinInGraph = updateCheckinInGraph(nodeType, component.getUniqueId(), component.getLifecycleState(), modifier, owner);
- if (!updateCheckinInGraph.equals(StorageOperationStatus.OK)) {
- log.error("failed to update state of resource {}. status={}", component.getUniqueId(), updateCheckinInGraph);
- return Either.right(updateCheckinInGraph);
- }
- LifecycleStateEnum state = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN;
- ComponentParametersView componentParametersView = buildFilterForFetchComponentAfterChangeState();
- result = updateComponentMD(component, modifier, state, nodeType, componentParametersView);
- if (result.isRight()) {
- log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), state, result.right().value());
- }
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- private ComponentParametersView buildFilterForFetchComponentAfterChangeState() {
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreUsers(false);
- // Used when we running multiple change states and want to use the
- // result from another change
- // state(LifecycleOperationTest.certificationStatusChange)
- componentParametersView.setIgnoreCategories(false);
- return componentParametersView;
- }
-
- private StorageOperationStatus updateCheckinInGraph(NodeTypeEnum componentType, String componentId, LifecycleStateEnum state, User modifier, User owner) {
-
- // check if we cancel rfc
- if (state.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) {
-
- // remove last checkin
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- UniqueIdData resourceData = new UniqueIdData(componentType, componentId);
- Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
- if (deleteResult.isRight()) {
- log.debug("failed to update last state relation");
- return StorageOperationStatus.INCONSISTENCY;
- }
- }
-
- // remove CHECKOUT relation
- StorageOperationStatus removeUserToResourceRelation = removeUserToResourceRelation(componentType, owner.getUserId(), componentId, GraphEdgeLabels.STATE);
- if (!removeUserToResourceRelation.equals(StorageOperationStatus.OK)) {
- return removeUserToResourceRelation;
- }
-
- // create CHECKIN relation
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- StorageOperationStatus createUserToResourceRelation = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props);
- if (!createUserToResourceRelation.equals(StorageOperationStatus.OK)) {
- return createUserToResourceRelation;
- }
-
- return StorageOperationStatus.OK;
- }
-
- @Override
- public Either<? extends Component, StorageOperationStatus> requestCertificationComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction) {
- Either<? extends Component, StorageOperationStatus> result = null;
- try {
- StorageOperationStatus updateRfcOnGraph = updateRfcOnGraph(nodeType, component.getUniqueId(), component.getLifecycleState(), modifier, owner);
- if (!updateRfcOnGraph.equals(StorageOperationStatus.OK)) {
- log.error("failed to update state of resource {}. status={}", component.getUniqueId(), updateRfcOnGraph);
- return Either.right(updateRfcOnGraph);
- }
-
- LifecycleStateEnum state = LifecycleStateEnum.READY_FOR_CERTIFICATION;
-
- ComponentParametersView componentParametersView = buildFilterForFetchComponentAfterChangeState();
-
- result = updateComponentMD(component, modifier, state, nodeType, componentParametersView);
- if (result.isRight()) {
- log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), state, result.right().value());
- return result;
- }
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- private StorageOperationStatus updateRfcOnGraph(NodeTypeEnum componentType, String componentId, LifecycleStateEnum state, User modifier, User owner) {
-
- if (state.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
- // if this is atomic checkin + RFC: create checkin relation
-
- // remove CHECKOUT relation
- StorageOperationStatus relationStatus = removeUserToResourceRelation(componentType, owner.getUserId(), componentId, GraphEdgeLabels.STATE);
- if (!relationStatus.equals(StorageOperationStatus.OK)) {
- return relationStatus;
- }
-
- // create CHECKIN relation
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- relationStatus = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.LAST_STATE, props);
- if (!relationStatus.equals(StorageOperationStatus.OK)) {
- return relationStatus;
- }
- } else {
- StorageOperationStatus changeStatus = changeRelationLabel(componentType, componentId, owner, GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE);
- if (!changeStatus.equals(StorageOperationStatus.OK)) {
- return changeStatus;
- }
- }
-
- // create RFC relation
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- StorageOperationStatus changeRelationLabel = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props);
- if (!changeRelationLabel.equals(StorageOperationStatus.OK)) {
- return changeRelationLabel;
- }
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus changeRelationLabel(NodeTypeEnum componentType, String componentId, User owner, GraphEdgeLabels prevLabel, GraphEdgeLabels toLabel) {
- UniqueIdData resourceV = new UniqueIdData(componentType, componentId);
- UserData userV = new UserData();
- userV.setUserId(owner.getUserId());
- Either<GraphRelation, TitanOperationStatus> replaceRelationLabelResult = titanGenericDao.replaceRelationLabel(userV, resourceV, prevLabel, toLabel);
- if (replaceRelationLabelResult.isRight()) {
- log.error("failed to replace label from last state to state");
- return DaoStatusConverter.convertTitanStatusToStorageStatus(replaceRelationLabelResult.right().value());
- }
- return StorageOperationStatus.OK;
- }
-
- @Override
- public Either<? extends Component, StorageOperationStatus> startComponentCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction) {
- Either<? extends Component, StorageOperationStatus> result = null;
- try {
- StorageOperationStatus updateOnGraph = updateStartCertificationOnGraph(nodeType, component.getUniqueId(), modifier, owner);
- if (!updateOnGraph.equals(StorageOperationStatus.OK)) {
- log.error("failed to update state of resource {}. status={}", component.getUniqueId(), updateOnGraph);
- return Either.right(updateOnGraph);
- }
-
- LifecycleStateEnum state = LifecycleStateEnum.CERTIFICATION_IN_PROGRESS;
- ComponentParametersView componentParametersView = buildFilterForFetchComponentAfterChangeState();
-
- result = updateComponentMD(component, modifier, state, nodeType, componentParametersView);
- if (result.isRight()) {
- log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), state, result.right().value());
- }
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- private StorageOperationStatus updateStartCertificationOnGraph(NodeTypeEnum componentType, String componentId, User modifier, User owner) {
- StorageOperationStatus changeRelationLabel = changeRelationLabel(componentType, componentId, owner, GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE);
- if (!changeRelationLabel.equals(StorageOperationStatus.OK)) {
- return changeRelationLabel;
- }
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
-
- StorageOperationStatus createUserToResourceRelation = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props);
- if (!createUserToResourceRelation.equals(StorageOperationStatus.OK)) {
- return createUserToResourceRelation;
- }
- return StorageOperationStatus.OK;
- }
-
- @Override
- public Either<? extends Component, StorageOperationStatus> certifyComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction) {
- Either<? extends Component, StorageOperationStatus> result = null;
-
- try {
- String resourceIdBeforeCertify = component.getUniqueId();
- String[] versionParts = component.getVersion().split(VERSION_DELIMETER_REGEXP);
- Integer majorVersion = Integer.parseInt(versionParts[0]);
-
- // update old certified resource
- if (majorVersion > 0) {
- StorageOperationStatus updateLastCertifiedResource = StorageOperationStatus.OK;
- updateLastCertifiedResource = updateLastCertifiedComponent(component, majorVersion);
- if (!updateLastCertifiedResource.equals(StorageOperationStatus.OK)) {
- return Either.right(updateLastCertifiedResource);
- }
- }
-
- // clone the resource
- Either<? extends Component, StorageOperationStatus> createResourceResult = Either.right(StorageOperationStatus.GENERAL_ERROR);
- switch (nodeType) {
- case Service:
- case Resource:
- createResourceResult = cloneComponentForCertified(component, modifier, majorVersion);
- break;
- default:
- log.error("component object is with type {} . It's not supported type");
- result = Either.right(StorageOperationStatus.BAD_REQUEST);
- return result;
- }
-
- if (createResourceResult.isRight()) {
- log.error("failed to create new resource version for checkout.");
- result = createResourceResult;
- return createResourceResult;
- }
-
- Component certifiedResource = createResourceResult.left().value();
-
- // add rfc relation to preserve follower information
- StorageOperationStatus addRfcRelation = addRfcRelationToCertfiedComponent(nodeType, resourceIdBeforeCertify, certifiedResource.getUniqueId());
- if (!addRfcRelation.equals(StorageOperationStatus.OK)) {
- result = Either.right(addRfcRelation);
- return result;
- }
-
- result = Either.left(certifiedResource);
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- return result;
- }
-
- @Override
- public Either<Boolean, StorageOperationStatus> deleteOldComponentVersions(NodeTypeEnum nodeType, String componentName, String uuid, boolean inTransaction) {
-
- Either<Boolean, StorageOperationStatus> result = null;
- ComponentOperation componentOperation = getComponentOperation(nodeType);
-
- try {
- Either<List<Component>, StorageOperationStatus> oldVersionsToDelete = getComponentTempVersions(nodeType, uuid);
-
- if (oldVersionsToDelete.isRight()) {
- result = Either.right(oldVersionsToDelete.right().value());
- return result;
- }
-
- for (Component resourceToDelete : oldVersionsToDelete.left().value()) {
-
- Either<Component, StorageOperationStatus> updateResource = componentOperation.markComponentToDelete(resourceToDelete, inTransaction);
- if (updateResource.isRight()) {
- result = Either.right(updateResource.right().value());
- return result;
- }
- }
- result = Either.left(true);
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- private StorageOperationStatus addRfcRelationToCertfiedComponent(NodeTypeEnum componentType, String resourceIdBeforeCertify, String uniqueId) {
-
- // get user of certification request
- UniqueIdData componentV = new UniqueIdData(componentType, resourceIdBeforeCertify);
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<GraphRelation, TitanOperationStatus> rfcRelationResponse = titanGenericDao.getIncomingRelationByCriteria(componentV, GraphEdgeLabels.LAST_STATE, props);
- if (rfcRelationResponse.isRight()) {
- TitanOperationStatus status = rfcRelationResponse.right().value();
- log.error("failed to find rfc relation for component {}. status=", resourceIdBeforeCertify, status);
- return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- }
- GraphRelation rfcRelation = rfcRelationResponse.left().value();
- rfcRelation.setTo(new RelationEndPoint(componentType, GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId));
-
- Either<GraphRelation, TitanOperationStatus> createRelationResponse = titanGenericDao.createRelation(rfcRelation);
- if (createRelationResponse.isRight()) {
- TitanOperationStatus status = createRelationResponse.right().value();
- log.error("failed to create rfc relation for component {}. status=", uniqueId, status);
- return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- }
- return StorageOperationStatus.OK;
-
- }
-
- private StorageOperationStatus updateLastCertifiedComponent(Component component, Integer majorVersion) {
-
- NodeTypeEnum nodeType = component.getComponentType().getNodeType();
- ComponentOperation componentOperation = getComponentOperation(nodeType);
- Map<String, Object> additionalQueryParams = null;
- if (nodeType == NodeTypeEnum.Resource) {
- ResourceTypeEnum resourceType = ((Resource) component).getResourceType();
- additionalQueryParams = new HashMap<String, Object>();
- additionalQueryParams.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType.name());
- }
- Either<? extends Component, StorageOperationStatus> getLastCertifiedResponse = componentOperation.getComponentByNameAndVersion(component.getName(), majorVersion + VERSION_DELIMETER + "0", additionalQueryParams, true);
-
- if (getLastCertifiedResponse.isRight()) {
- log.error("failed to update last certified resource. status={}", getLastCertifiedResponse.right().value());
- return getLastCertifiedResponse.right().value();
- }
-
- Component lastCertified = getLastCertifiedResponse.left().value();
- lastCertified.setHighestVersion(false);
- Either<Component, StorageOperationStatus> updateResource = componentOperation.updateComponent(lastCertified, true);
- if (updateResource.isRight()) {
- log.error("failed to update last certified resource. status={}", updateResource.right().value());
- return updateResource.right().value();
- }
- return StorageOperationStatus.OK;
- }
-
- private Either<Component, StorageOperationStatus> cloneComponentForCheckout(Component component, NodeTypeEnum nodeType, User modifier) {
-
- ComponentOperation componentOperation = getComponentOperation(nodeType);
- String prevId = component.getUniqueId();
- // set new version
- Either<String, StorageOperationStatus> nextVersion = getNextVersion(component.getVersion());
- if (nextVersion.isRight()) {
- return Either.right(nextVersion.right().value());
- }
-
- // if checkout on certified service - init distribution status back
- if (nodeType == NodeTypeEnum.Service && component.getLifecycleState().equals(LifecycleStateEnum.CERTIFIED)) {
- ((Service) component).setDistributionStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
- }
-
- String version = nextVersion.left().value();
- component.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- component.setLastUpdateDate(null);
- component.setLastUpdaterUserId(modifier.getUserId());
- component.setHighestVersion(true);
-
- // check version of resource does not exist. Note that resource type VF
- // can have same name as resource type VFC
- Map<String, Object> additionalQueryParams = null;
- if (nodeType == NodeTypeEnum.Resource) {
- ResourceTypeEnum resourceType = ((Resource) component).getResourceType();
- additionalQueryParams = new HashMap<String, Object>();
- additionalQueryParams.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType.name());
- }
- String name = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
- Either<Component, StorageOperationStatus> alreadyExistResult = componentOperation.getComponentByNameAndVersion(name, version, additionalQueryParams, true);
- if (alreadyExistResult.isLeft()) {
- log.debug("Component with name {} and version {} already exist", name, version);
- return Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS);
-
- }
-
- StorageOperationStatus storageOperationStatus = alreadyExistResult.right().value();
- if (storageOperationStatus != StorageOperationStatus.NOT_FOUND) {
- log.debug("Unexpected error when checking if component with name {} and version {} already exist, error: {}", name, version, storageOperationStatus);
- return Either.right(storageOperationStatus);
- }
-
- Either<Component, StorageOperationStatus> cloneComponentResponse = componentOperation.cloneComponent(component, version, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, true);
-
- return cloneComponentResponse;
- }
-
- private Either<String, StorageOperationStatus> getNextVersion(String currVersion) {
- String[] versionParts = currVersion.split(VERSION_DELIMETER_REGEXP);
- if (versionParts == null || versionParts.length != 2) {
- log.error("invalid version {}", currVersion);
- return Either.right(StorageOperationStatus.BAD_REQUEST);
- }
-
- Integer minorVersion = Integer.parseInt(versionParts[1]) + 1;
- String newVersion = versionParts[0] + VERSION_DELIMETER + minorVersion;
- return Either.left(newVersion);
- }
-
- private StorageOperationStatus setRelationForCancelCertification(LifecycleStateEnum nextState, NodeTypeEnum componentType, String componentId) {
-
- StorageOperationStatus result = StorageOperationStatus.GENERAL_ERROR;
- Map<String, Object> props = new HashMap<String, Object>();
- UniqueIdData componentData = new UniqueIdData(componentType, componentId);
-
- // delete relation CERTIFICATION_IN_PROGRESS
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
-
- Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.STATE, props);
- if (deleteResult.isRight()) {
- log.debug("failed to update last state relation");
- result = StorageOperationStatus.INCONSISTENCY;
- return result;
- }
-
- // delete relation READY_FOR_CERTIFICATION (LAST_STATE)
- props.put(GraphPropertiesDictionary.STATE.getProperty(), nextState);
-
- deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, props);
- if (deleteResult.isRight()) {
- log.debug("failed to update last state relation");
- result = StorageOperationStatus.INCONSISTENCY;
- return result;
- }
- GraphRelation origRelation = deleteResult.left().value();
-
- // create relation READY_FOR_CERTIFICATION (STATE)
- UserData user = new UserData();
- user.setUserId((String) origRelation.getFrom().getIdValue());
- Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(user, componentData, GraphEdgeLabels.STATE, origRelation.toGraphMap());
-
- if (createRelationResult.isRight()) {
- log.error("failed to update last state relation. status={}", createRelationResult.right().value());
- result = StorageOperationStatus.INCONSISTENCY;
- return result;
- }
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus setRelationForFailCertification(LifecycleStateEnum nextState, NodeTypeEnum componentType, String componentId) {
-
- StorageOperationStatus result = null;
- Map<String, Object> props = new HashMap<String, Object>();
- UniqueIdData componentData = new UniqueIdData(componentType, componentId);
-
- // delete relation CERTIFICATION_IN_PROGRESS
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
-
- Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.STATE, props);
- if (deleteResult.isRight()) {
- log.debug("failed to update last state relation");
- result = StorageOperationStatus.INCONSISTENCY;
- return result;
- }
-
- // delete relation READY_FOR_CERTIFICATION
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
-
- deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, props);
- if (deleteResult.isRight()) {
- log.debug("failed to update last state relation");
- result = StorageOperationStatus.INCONSISTENCY;
- return result;
- }
-
- // delete relation NOT_CERTIFIED_CHECKIN (in order to change to STATE)
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, props);
- if (deleteResult.isRight()) {
- log.debug("failed to update last state relation");
- result = StorageOperationStatus.INCONSISTENCY;
- return result;
- }
-
- // create new STATE relation NOT_CERTIFIED_CHECKIN
- GraphRelation origRelation = deleteResult.left().value();
- UserData user = new UserData();
- user.setUserId((String) origRelation.getFrom().getIdValue());
- Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(user, componentData, GraphEdgeLabels.STATE, origRelation.toGraphMap());
-
- if (createRelationResult.isRight()) {
- log.debug("failed to update last state relation");
- result = StorageOperationStatus.INCONSISTENCY;
- return result;
- }
-
- // delete relation LAST_MODIFIER (in order to change tester to designer)
- deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_MODIFIER, null);
- if (deleteResult.isRight()) {
- log.debug("failed to update last modifier relation");
- result = StorageOperationStatus.INCONSISTENCY;
- return result;
- }
-
- // create new LAST_MODIFIER relation
- origRelation = deleteResult.left().value();
- createRelationResult = titanGenericDao.createRelation(user, componentData, GraphEdgeLabels.LAST_MODIFIER, origRelation.toGraphMap());
- if (createRelationResult.isRight()) {
- log.debug("failed to update last state relation");
- result = StorageOperationStatus.INCONSISTENCY;
- return result;
- }
-
- return StorageOperationStatus.OK;
- }
-
- /**
- * update service metadata - lastUpdater and state
- *
- * @param component
- * @param modifier
- * @param nextState
- * @return
- */
- private Either<Component, StorageOperationStatus> updateComponentMD(Component component, User modifier, LifecycleStateEnum nextState, NodeTypeEnum nodeType, ComponentParametersView returnedComponentParametersViewFilter) {
-
- if (returnedComponentParametersViewFilter == null) {
- returnedComponentParametersViewFilter = new ComponentParametersView();
- }
-
- Either<Component, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR);
- component.setLastUpdateDate(null);
- component.setLastUpdaterUserId(modifier.getUserId());
-
- ComponentOperation componentOperation = getComponentOperation(nodeType);
- ComponentParametersView filterParametersView = buildFilterForFetchComponentAfterChangeState();
- log.debug("updateComponentMD::updateComponentFilterResult start");
- result = componentOperation.updateComponentFilterResult(component, true, filterParametersView);
- log.debug("updateComponentMD::updateComponentFilterResult end");
- if (result.isRight()) {
- log.debug("Failed to update component for certification request, error: {}", result.right().value());
- return result;
- }
- log.debug("updateComponentMD::getAndUpdateMetadata start");
- // get service MD
- Either<ComponentMetadataData, TitanOperationStatus> componentDataResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), component.getUniqueId(), ComponentMetadataData.class);
- if (componentDataResult.isRight()) {
- log.debug("failed to get service data from graph");
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentDataResult.right().value()));
- }
-
- // set state on resource
- ComponentMetadataData componentData = componentDataResult.left().value();
- componentData.getMetadataDataDefinition().setState(nextState.name());
- component.setLifecycleState(nextState);
- Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class);
- log.debug("updateComponentMD::getAndUpdateMetadata end");
- if (updateNode.isRight()) {
- log.error("Failed to update component {}. status is {}", component.getUniqueId(), updateNode.right().value());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
- return result;
- }
- log.debug("updateComponentMD::getAndUpdateMetadata start");
- Either<Object, StorageOperationStatus> serviceAfterChange = componentOperation.getComponent(component.getUniqueId(), returnedComponentParametersViewFilter, true);
- log.debug("updateComponentMD::getAndUpdateMetadata end");
- if (serviceAfterChange.isRight()) {
- log.error("Failed to get component {} after change. status is {}", component.getUniqueId(), updateNode.right().value());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
- return result;
- }
- return Either.left((Component) serviceAfterChange.left().value());
- }
-
- /**
- * update resouce metadata - lastUpdater and state
- *
- * @param resource
- * @param modifier
- * @param nextState
- * @return
- */
- private Either<Resource, StorageOperationStatus> updateResourceMD(Resource resource, User modifier, LifecycleStateEnum nextState) {
-
- Either<Resource, StorageOperationStatus> result;
- resource.setLastUpdateDate(null);
- resource.setLastUpdaterUserId(modifier.getUserId());
-
- result = resourceOperation.updateResource(resource, true);
- if (result.isRight()) {
- log.debug("failed to update resource for certification request.");
- return result;
- }
- // get resource MD
- Either<ResourceMetadataData, TitanOperationStatus> resourceDataResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId(), ResourceMetadataData.class);
- if (resourceDataResult.isRight()) {
- log.debug("failed to get resource data from graph");
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceDataResult.right().value()));
- }
-
- // set state on resource
- ResourceMetadataData resourceData = resourceDataResult.left().value();
- resourceData.getMetadataDataDefinition().setState(nextState.name());
- resource.setLifecycleState(nextState);
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(resourceData, ResourceMetadataData.class);
-
- if (updateNode.isRight()) {
- log.error("Failed to update resource {}. status is {}", resource.getUniqueId(), updateNode.right().value());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
- return result;
- }
- return Either.left(resource);
- }
-
- private Either<List<Component>, StorageOperationStatus> getComponentTempVersions(NodeTypeEnum nodeType, String uuid) {
-
- Either<List<Component>, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR);
- List<Component> componentList = new ArrayList<Component>();
- ComponentOperation componentOperation = getComponentOperation(nodeType);
-
- Map<String, Object> hasProps = new HashMap<String, Object>();
- Map<String, Object> hasNotProps = new HashMap<String, Object>();
-
- createOldVersionsCriteria(nodeType, uuid, hasProps, hasNotProps);
-
- Either<List<ComponentMetadataData>, TitanOperationStatus> getByCriteria = titanGenericDao.getByCriteria(nodeType, hasProps, hasNotProps, ComponentMetadataData.class);
-
- if (getByCriteria.isRight()) {
- log.error("failed to get old versions for component, type:{}, id: {}", nodeType, uuid);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getByCriteria.right().value()));
- return result;
- }
-
- List<ComponentMetadataData> oldVersionComponents = getByCriteria.left().value();
- for (ComponentMetadataData component : oldVersionComponents) {
- Either<Component, StorageOperationStatus> resourceRes = componentOperation.getComponent(component.getMetadataDataDefinition().getUniqueId(), true);
- if (resourceRes.isRight()) {
- result = Either.right(resourceRes.right().value());
- return result;
- } else {
- componentList.add(resourceRes.left().value());
- }
- }
- result = Either.left(componentList);
- return result;
- }
-
- /*
- * private Either<List<Service>, StorageOperationStatus> getServiceTempVersions(NodeTypeEnum nodeType, String uuid) {
- *
- * Either<List<Service>, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR); List<Service> resourceList = new ArrayList<Service>();
- *
- * Map<String, Object> hasProps = new HashMap<String, Object>(); Map<String, Object> hasNotProps = new HashMap<String, Object>();
- *
- * createOldVersionsCriteria(nodeType, uuid, hasProps, hasNotProps);
- *
- * Either<List<ServiceMetadataData>, TitanOperationStatus> getByCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, hasProps, hasNotProps, ServiceMetadataData.class);
- *
- * if (getByCriteria.isRight()) { log.error("failed to get old versions for {}", uuid); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus( getByCriteria.right().value())); return result; }
- *
- * List<ServiceMetadataData> oldVersionResources = getByCriteria.left().value(); for (ServiceMetadataData resource : oldVersionResources) { Either<Service, StorageOperationStatus> resourceRes = serviceOperation.getService((String)
- * resource.getUniqueId(), true); if (resourceRes.isRight()) { result = Either.right(resourceRes.right().value()); return result; } else { resourceList.add(resourceRes.left().value()); } } result = Either.left(resourceList); return result; }
- */
- private void createOldVersionsCriteria(NodeTypeEnum nodeType, String uuid, Map<String, Object> hasProps, Map<String, Object> hasNotProps) {
-
- hasProps.put(GraphPropertiesDictionary.UUID.getProperty(), uuid);
- hasProps.put(GraphPropertiesDictionary.LABEL.getProperty(), nodeType.name().toLowerCase());
- hasNotProps.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
- }
-
- private Either<? extends Component, StorageOperationStatus> updateOldComponentBeforeUndoCheckout(ComponentOperation componentOperation, Component prevComponent, Component currentComponent, String previousVersion, NodeTypeEnum nodeType,
- boolean inTransaction) {
-
- log.debug("update previous version of component");
- Map<String, Object> additionalQueryParams = new HashMap<String, Object>();
-
- if (nodeType == NodeTypeEnum.Resource) {
- ResourceTypeEnum resourceType = ((Resource) currentComponent).getResourceType();
-
- additionalQueryParams.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType.name());
- }
- ComponentMetadataDataDefinition metadataDataDefinition = currentComponent.getComponentMetadataDefinition().getMetadataDataDefinition();
- Either<? extends Component, StorageOperationStatus> getOlderCompResult = componentOperation.getComponentByNameAndVersion(metadataDataDefinition.getName(), previousVersion, additionalQueryParams, true);
-
- // if previous version exist - set it as current version
- if (getOlderCompResult.isRight()) {
- if (StorageOperationStatus.NOT_FOUND.equals(getOlderCompResult.right().value())) {
- log.debug("No components by name and version: {} - {}", metadataDataDefinition.getName(), previousVersion);
- log.debug("Name may have changed, since the version isn't certified try to fetch by UUID {}", metadataDataDefinition.getUUID());
- additionalQueryParams.clear();
- additionalQueryParams.put(GraphPropertiesDictionary.UUID.getProperty(), metadataDataDefinition.getUUID());
- additionalQueryParams.put(GraphPropertiesDictionary.VERSION.getProperty(), previousVersion);
-
- Either<List<ComponentMetadataData>, TitanOperationStatus> byUUID = titanGenericDao.getByCriteria(nodeType, additionalQueryParams, ComponentMetadataData.class);
- if (byUUID.isRight()) {
- log.debug("Failed to fetch by UUID {}", metadataDataDefinition.getUUID());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byUUID.right().value()));
- }
- String prevVersionId = (String) byUUID.left().value().get(0).getUniqueId();
- Either<? extends Component, StorageOperationStatus> component = componentOperation.getComponent(prevVersionId, inTransaction);
- if (component.isRight()) {
- log.debug("Failed to fetch previous component by ID {}", prevVersionId);
- return Either.right(component.right().value());
- }
- prevComponent = component.left().value();
- } else {
- log.error("failed to find previous version. status={} ", getOlderCompResult.right().value());
- return getOlderCompResult;
- }
- } else {
- prevComponent = getOlderCompResult.left().value();
- }
-
- // if last resource is certified - don't touch it.
- if (prevComponent.getVersion().endsWith(".0")) {
- return Either.left(prevComponent);
- }
-
- prevComponent.setHighestVersion(true);
- Either<Component, StorageOperationStatus> updateCompResult = componentOperation.updateComponent(prevComponent, inTransaction);
- if (updateCompResult.isRight()) {
- log.debug("failed to update prev version of component");
- return updateCompResult;
- }
-
- User user = new User();
- user.setUserId(prevComponent.getLastUpdaterUserId());
- StorageOperationStatus changeStateRelation = changeStateRelation(nodeType, prevComponent.getUniqueId(), user, GraphEdgeLabels.LAST_STATE, GraphEdgeLabels.STATE);
- if (!changeStateRelation.equals(StorageOperationStatus.OK)) {
- return Either.right(changeStateRelation);
- }
-
- return Either.left(prevComponent);
- }
-
- private StorageOperationStatus changeStateRelation(NodeTypeEnum nodeType, String componentId, User currentOwner, GraphEdgeLabels from, GraphEdgeLabels to) {
- UniqueIdData componentData = new UniqueIdData(nodeType, componentId);
- UserData userData = new UserData();
- userData.setUserId(currentOwner.getUserId());
- Either<GraphRelation, TitanOperationStatus> replaceRelationLabelResult = titanGenericDao.replaceRelationLabel(userData, componentData, from, to);
- if (replaceRelationLabelResult.isRight()) {
- TitanOperationStatus titanStatus = replaceRelationLabelResult.right().value();
- log.error("failed to replace label from {} to {}. status = {}", from, to, titanStatus);
- StorageOperationStatus storageStatus = StorageOperationStatus.INCONSISTENCY;
- if (!titanStatus.equals(TitanOperationStatus.INVALID_ID)) {
- storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
- }
- return storageStatus;
- }
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus removeUserToResourceRelation(NodeTypeEnum componentType, String idFrom, String idTo, GraphEdgeLabels label) {
-
- UniqueIdData componentV = new UniqueIdData(componentType, idTo);
- UserData userV = new UserData();
- userV.setUserId(idFrom);
- // delete relation
- Either<GraphRelation, TitanOperationStatus> deleteRelationResult = titanGenericDao.deleteRelation(userV, componentV, label);
- if (deleteRelationResult.isRight()) {
- log.error("failed to delete relation. status={}", deleteRelationResult.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteRelationResult.right().value());
- }
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus createUserToResourceRelation(NodeTypeEnum componentType, String idFrom, String idTo, GraphEdgeLabels label, Map<String, Object> props) {
-
- UniqueIdData componentV = new UniqueIdData(componentType, idTo);
- UserData userV = new UserData();
- userV.setUserId(idFrom);
- // create relation
- Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(userV, componentV, label, props);
- if (createRelationResult.isRight()) {
- log.error("failed to create relation. status={}", createRelationResult.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(createRelationResult.right().value());
- }
- return StorageOperationStatus.OK;
- }
-
- @Override
- public Either<? extends Component, StorageOperationStatus> cancelOrFailCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, LifecycleStateEnum nextState, boolean inTransaction) {
-
- Either<? extends Component, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR);
- try {
-
- ComponentParametersView componentParametersView = buildFilterForFetchComponentAfterChangeState();
- result = updateComponentMD(component, modifier, nextState, nodeType, componentParametersView);
- if (result.isRight()) {
- log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), nextState, result.right().value());
- return result;
- }
- StorageOperationStatus status = StorageOperationStatus.OK;
- // cancel certification process
- if (nextState.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) {
- status = setRelationForCancelCertification(nextState, nodeType, component.getUniqueId());
-
- } // fail certification
- else if (nextState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN)) {
- status = setRelationForFailCertification(nextState, nodeType, component.getUniqueId());
- }
-
- if (!status.equals(StorageOperationStatus.OK)) {
- result = Either.right(status);
- }
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- return result;
- }
-
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java
deleted file mode 100644
index 3d4fba36df..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java
+++ /dev/null
@@ -1,957 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-import java.util.Set;
-
-import com.thinkaurelius.titan.core.TitanTransaction;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.category.CategoryDataDefinition;
-import org.openecomp.sdc.be.datatypes.category.GroupingDataDefinition;
-import org.openecomp.sdc.be.datatypes.category.SubCategoryDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ProductMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.*;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.GroupingDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.be.model.operations.api.IProductOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
-import org.openecomp.sdc.be.resources.data.ProductMetadataData;
-import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
-import org.openecomp.sdc.be.resources.data.UserData;
-import org.openecomp.sdc.be.resources.data.category.CategoryData;
-import org.openecomp.sdc.be.resources.data.category.GroupingData;
-import org.openecomp.sdc.be.resources.data.category.SubCategoryData;
-import org.openecomp.sdc.common.util.ValidationUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.thinkaurelius.titan.core.TitanGraph;
-
-import fj.data.Either;
-
-@org.springframework.stereotype.Component("product-operation")
-public class ProductOperation extends ComponentOperation implements IProductOperation {
-
- private static Logger log = LoggerFactory.getLogger(ProductOperation.class.getName());
-
- public ProductOperation() {
- log.debug("ProductOperation created");
- }
-
- @Override
- protected ComponentMetadataData getMetaDataFromComponent(Component component) {
- return getProductMetadataDataFromProduct((Product) component);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> Either<T, StorageOperationStatus> getComponent(String id, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) getProduct(id, inTransaction);
- }
-
- // public <T> Either<T, StorageOperationStatus> getComponent_tx(String id,
- // boolean inTransaction) {
- // return (Either<T, StorageOperationStatus>) getProduct_tx(id,
- // inTransaction);
- // }
-
- @SuppressWarnings("unchecked")
- @Override
- protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) getByNamesAndVersion(GraphPropertiesDictionary.NAME.getProperty(), name, version, additionalParams, inTransaction);
- }
-
- @Override
- public <T> Either<T, StorageOperationStatus> getLightComponent(String id, boolean inTransaction) {
- return getLightComponent(id, NodeTypeEnum.Product, inTransaction);
- }
-
- @Override
- public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
- return getFilteredComponents(filters, inTransaction, NodeTypeEnum.Product);
- }
-
- private Product convertProductDataToProduct(ProductMetadataData productData) {
- ProductMetadataDefinition productMetadataDefinition = new ProductMetadataDefinition((ProductMetadataDataDefinition) productData.getMetadataDataDefinition());
-
- Product product = new Product(productMetadataDefinition);
-
- return product;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> Either<T, StorageOperationStatus> updateComponent(T component, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) updateComponent((Component) component, inTransaction, titanGenericDao, Product.class, NodeTypeEnum.Product);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Either<Component, StorageOperationStatus> deleteComponent(String id, boolean inTransaction) {
- return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteProduct(id, inTransaction);
- }
-
- @Override
- public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T extends org.openecomp.sdc.be.model.Component> Either<T, StorageOperationStatus> getComponent(String id, Class<T> clazz) {
- return (Either<T, StorageOperationStatus>) getProduct(id, false);
- }
-
- @Override
- /**
- * Deletes the product node
- */
- public Either<Product, StorageOperationStatus> deleteProduct(String productId, boolean inTransaction) {
-
- Either<Product, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR);
-
- try {
-
- Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
- if (graphResult.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
- return result;
- }
-
- Either<ProductMetadataData, TitanOperationStatus> productNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Product), productId, ProductMetadataData.class);
- if (productNode.isRight()) {
- TitanOperationStatus status = productNode.right().value();
- log.error("Failed to find product {}. status is {}", productId, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- Either<Product, StorageOperationStatus> productRes = getProduct(productId, true);
- if (productRes.isRight()) {
- StorageOperationStatus status = productRes.right().value();
- log.error("Failed to find product {}.status is {}", productId, status);
- result = Either.right(status);
- return result;
- }
- Product product = productRes.left().value();
-
- Either<List<ComponentInstance>, StorageOperationStatus> deleteAllInstancesRes = componentInstanceOperation.deleteAllComponentInstances(productId, NodeTypeEnum.Product, true);
- log.debug("After deleting instances under product {}.Result is {}", productId, deleteAllInstancesRes);
- if (deleteAllInstancesRes.isRight()) {
- StorageOperationStatus status = deleteAllInstancesRes.right().value();
- if (status != StorageOperationStatus.NOT_FOUND) {
- log.error("Failed to delete instances under product {}.status is {}", productId, status);
- result = Either.right(status);
- return result;
- }
- }
-
- Either<ProductMetadataData, TitanOperationStatus> deleteProductNodeRes = titanGenericDao.deleteNode(productNode.left().value(), ProductMetadataData.class);
- if (deleteProductNodeRes.isRight()) {
- TitanOperationStatus status = deleteProductNodeRes.right().value();
- log.error("Failed to delete product node {}. status is {}", productId, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- result = Either.left(product);
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("deleteProduct operation : Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("deleteProduct operation : Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public Either<List<Product>, StorageOperationStatus> getProductCatalogData(boolean inTransaction) {
-
- long start = System.currentTimeMillis();
- try {
- /*
- * Map<String, Object> propertiesToMatch = new HashMap<>();
- *
- * propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty (), LifecycleStateEnum.CERTIFIED.name()); Either<List<ProductMetadataData>, TitanOperationStatus> lastVersionNodes = getLastVersion(NodeTypeEnum.Product,
- * propertiesToMatch, ProductMetadataData.class); if (lastVersionNodes.isRight() && lastVersionNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus
- * (lastVersionNodes.right().value())); } List<ProductMetadataData> notCertifiedHighest = (lastVersionNodes.isLeft() ? lastVersionNodes.left().value() : new ArrayList<ProductMetadataData>());
- *
- * propertiesToMatch.put(GraphPropertiesDictionary. IS_HIGHEST_VERSION.getProperty(), true); Either<List<ProductMetadataData>, TitanOperationStatus> componentsNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Product, propertiesToMatch,
- * ProductMetadataData.class); if (componentsNodes.isRight() && componentsNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus
- * (componentsNodes.right().value())); } List<ProductMetadataData> certifiedHighest = (componentsNodes.isLeft() ? componentsNodes.left().value() : new ArrayList<ProductMetadataData>()); Set<String> names = new HashSet<String>(); for
- * (ProductMetadataData data : notCertifiedHighest) { String name = data.getMetadataDataDefinition().getName(); names.add(name); }
- *
- * for (ProductMetadataData data : certifiedHighest) { String productName = data.getMetadataDataDefinition().getName(); if (!names.contains(productName)) { notCertifiedHighest.add(data); } }
- */
- Either<List<ProductMetadataData>, TitanOperationStatus> listOfHighestComponents = this.getListOfHighestComponents(NodeTypeEnum.Product, ProductMetadataData.class);
- if (listOfHighestComponents.isRight() && listOfHighestComponents.right().value() != TitanOperationStatus.NOT_FOUND) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestComponents.right().value()));
- }
-
- List<ProductMetadataData> notCertifiedHighest = listOfHighestComponents.left().value();
-
- List<Product> result = new ArrayList<>();
-
- if (notCertifiedHighest != null && false == notCertifiedHighest.isEmpty()) {
-
- // fetch from cache
- long startFetchAllFromCache = System.currentTimeMillis();
-
- Map<String, Long> components = notCertifiedHighest.stream().collect(Collectors.toMap(p -> p.getMetadataDataDefinition().getUniqueId(), p -> p.getMetadataDataDefinition().getLastUpdateDate()));
-
- Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> componentsFromCacheForCatalog = this.getComponentsFromCacheForCatalog(components, ComponentTypeEnum.PRODUCT);
- if (componentsFromCacheForCatalog.isLeft()) {
- ImmutablePair<List<Component>, Set<String>> immutablePair = componentsFromCacheForCatalog.left().value();
- List<Component> list = immutablePair.getLeft();
- if (list != null) {
- for (Component component : list) {
- result.add((Product) component);
- }
- List<String> addedUids = list.stream().map(p -> p.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId()).collect(Collectors.toList());
- notCertifiedHighest = notCertifiedHighest.stream().filter(p -> false == addedUids.contains(p.getMetadataDataDefinition().getUniqueId())).collect(Collectors.toList());
- }
- }
- long endFetchAllFromCache = System.currentTimeMillis();
- log.debug("Fetch all catalog products metadata from cache took {} ms", (endFetchAllFromCache - startFetchAllFromCache));
- log.debug("The number of products added to catalog from cache is {}", result.size());
-
- log.debug("The number of products needed to be fetch as light component is {}", notCertifiedHighest.size());
-
- for (ProductMetadataData data : notCertifiedHighest) {
- Either<Product, StorageOperationStatus> component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction);
- if (component.isRight()) {
- log.debug("Failed to get product for id = {}, error : {}. skip product", data.getUniqueId(), component.right().value());
- } else {
- // get all versions
- Product product = component.left().value();
- // setAllVersions(product);
-
- result.add(product);
- }
- }
- }
- return Either.left(result);
- } finally {
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- log.debug("Fetch all catalog products took {} ms", System.currentTimeMillis() - start);
- }
- }
-
- @Override
- public Either<Product, StorageOperationStatus> createProduct(Product product) {
- return createProduct(product, false);
- }
-
- @Override
- public Either<Product, StorageOperationStatus> createProduct(Product product, boolean inTransaction) {
- Either<Product, StorageOperationStatus> result = null;
-
- try {
-
- ProductMetadataData productData = getProductMetadataDataFromProduct(product);
- addComponentInternalFields(productData);
- String uniqueId = (String) productData.getUniqueId();
- generateUUID(product);
-
- String userId = product.getCreatorUserId();
-
- Either<UserData, TitanOperationStatus> findUser = findUser(userId);
-
- if (findUser.isRight()) {
- TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user {} in the graph. status is {}", userId, status);
- return sendError(status, StorageOperationStatus.USER_NOT_FOUND);
- }
-
- UserData creatorUserData = findUser.left().value();
- UserData updaterUserData = creatorUserData;
- String updaterUserId = product.getLastUpdaterUserId();
- if (updaterUserId != null && !updaterUserId.equals(userId)) {
- findUser = findUser(updaterUserId);
- if (findUser.isRight()) {
- TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user {} in the graph. status is {}", userId, status);
- return sendError(status, StorageOperationStatus.USER_NOT_FOUND);
- } else {
- updaterUserData = findUser.left().value();
- }
- }
-
- log.trace("Creating tags for product {}", uniqueId);
- StorageOperationStatus storageOperationStatus = createTagsForComponent(product);
- if (storageOperationStatus != StorageOperationStatus.OK) {
- return Either.right(storageOperationStatus);
- }
-
- log.trace("Finding groupings for product {}", uniqueId);
- Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(NodeTypeEnum.ProductGrouping, product);
- if (findGroupingsForComponent.isRight()) {
- return Either.right(findGroupingsForComponent.right().value());
- }
- List<GroupingData> groupingDataToAssociate = findGroupingsForComponent.left().value();
-
- log.debug("try to create product node on graph for id {}", uniqueId);
- Either<ProductMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(productData, ProductMetadataData.class);
- if (createNode.isRight()) {
- TitanOperationStatus status = createNode.right().value();
- log.error("Error returned after creating product data node {}. Status returned is {}", productData, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- log.debug("product node created on graph for id {}", productData.getUniqueId());
-
- TitanOperationStatus associateMetadata = associateMetadataToComponent(productData, creatorUserData, updaterUserData, null, null);
- if (associateMetadata != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateMetadata));
- return result;
- }
-
- TitanOperationStatus associateCategories = associateCategoriesToProduct(productData, groupingDataToAssociate);
- if (associateCategories != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateCategories));
- return result;
- }
-
- result = getProduct(uniqueId, true);
- if (result.isRight()) {
- log.error("Cannot get full product from the graph. status is {}", result.right().value());
- return Either.right(result.right().value());
- }
-
- if (log.isDebugEnabled()) {
- String json = prettyJson.toJson(result.left().value());
- log.debug("Product retrieved is {}", json);
- }
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- private TitanOperationStatus associateCategoriesToProduct(ProductMetadataData productData, List<GroupingData> groupingDataToAssociate) {
- for (GroupingData groupingData : groupingDataToAssociate) {
- GraphEdgeLabels groupingLabel = GraphEdgeLabels.CATEGORIZED_TO;
- Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.createRelation(productData, groupingData, groupingLabel, null);
- log.debug("After associating grouping {} to product {}. Edge type is {}", groupingData, productData, groupingLabel);
- if (result.isRight()) {
- return result.right().value();
- }
- }
- log.trace("All groupings associated succesfully to product {}", productData);
- return TitanOperationStatus.OK;
- }
-
- private TitanOperationStatus dissociateCategoriesFromProduct(ProductMetadataData productData, List<GroupingData> groupingDataToDissociate) {
- for (GroupingData groupingData : groupingDataToDissociate) {
- GraphEdgeLabels groupingLabel = GraphEdgeLabels.CATEGORIZED_TO;
- Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.deleteRelation(productData, groupingData, groupingLabel);
- log.debug("After dissociating grouping {} from product {}. Edge type is {}", groupingData, productData, groupingLabel);
- if (result.isRight()) {
- return result.right().value();
- }
- }
- log.trace("All groupings dissociated succesfully from product {}", productData);
- return TitanOperationStatus.OK;
- }
-
- private Either<Product, StorageOperationStatus> getProduct(String uniqueId, boolean inTransaction) {
- ComponentParametersView componentParametersView = new ComponentParametersView();
- return getProduct(uniqueId, componentParametersView, inTransaction);
- }
-
- private Either<Product, StorageOperationStatus> getProduct(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction) {
- Product product = null;
- Either<Product, StorageOperationStatus> result = null;
- try {
-
- NodeTypeEnum productNodeType = NodeTypeEnum.Product;
- NodeTypeEnum compInstNodeType = NodeTypeEnum.Service;
-
- Either<ProductMetadataData, StorageOperationStatus> getComponentByLabel = getComponentByLabelAndId(uniqueId, productNodeType, ProductMetadataData.class);
- if (getComponentByLabel.isRight()) {
- result = Either.right(getComponentByLabel.right().value());
- return result;
- }
- ProductMetadataData productData = getComponentByLabel.left().value();
-
- // Try to fetch resource from the cache. The resource will be
- // fetched only if the time on the cache equals to
- // the time on the graph.
- Either<Product, ActionStatus> componentFromCacheIfUpToDate = this.getComponentFromCacheIfUpToDate(uniqueId, productData, componentParametersView, Product.class, ComponentTypeEnum.PRODUCT);
- if (componentFromCacheIfUpToDate.isLeft()) {
- Product cachedProduct = componentFromCacheIfUpToDate.left().value();
- log.debug("Product {} with uid {} was fetched from cache.", cachedProduct.getName(), cachedProduct.getUniqueId());
- return Either.left(cachedProduct);
- }
-
- product = convertProductDataToProduct(productData);
-
- TitanOperationStatus status = null;
- if (false == componentParametersView.isIgnoreUsers()) {
- status = setComponentCreatorFromGraph(product, uniqueId, productNodeType);
- if (status != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- status = setComponentLastModifierFromGraph(product, uniqueId, productNodeType);
- if (status != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
-
- }
- }
- if (false == componentParametersView.isIgnoreCategories()) {
- status = setComponentCategoriesFromGraph(product);
- if (status != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- }
-
- if (false == componentParametersView.isIgnoreComponentInstances() || false == componentParametersView.isIgnoreComponentInstancesProperties() || false == componentParametersView.isIgnoreCapabilities()
- || false == componentParametersView.isIgnoreRequirements()) {
- status = setComponentInstancesFromGraph(uniqueId, product, productNodeType, compInstNodeType);
- if (status != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
-
- }
- }
- if (false == componentParametersView.isIgnoreComponentInstancesProperties()) {
- status = setComponentInstancesPropertiesFromGraph(product);
- if (status != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- }
- if (false == componentParametersView.isIgnoreCapabilities()) {
- status = setCapabilitiesFromGraph(uniqueId, product, NodeTypeEnum.Product);
- if (status != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- }
- if (false == componentParametersView.isIgnoreRequirements()) {
- status = setRequirementsFromGraph(uniqueId, product, NodeTypeEnum.Product);
- if (status != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- }
-
- if (false == componentParametersView.isIgnoreAllVersions()) {
- status = setAllVersions(product);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
-
- result = Either.left(product);
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- titanGenericDao.rollback();
- } else {
- titanGenericDao.commit();
- }
- }
- }
- }
-
- // private Either<Product, StorageOperationStatus> getProduct_tx(String
- // uniqueId, boolean inTransaction) {
- // Product product = null;
- // Either<Product, StorageOperationStatus> result = null;
- // try {
- //
- // NodeTypeEnum productNodeType = NodeTypeEnum.Product;
- // NodeTypeEnum compInstNodeType = NodeTypeEnum.Service;
- //
- // Either<ProductMetadataData, StorageOperationStatus> getComponentByLabel =
- // getComponentByLabelAndId_tx(uniqueId, productNodeType,
- // ProductMetadataData.class);
- // if (getComponentByLabel.isRight()) {
- // result = Either.right(getComponentByLabel.right().value());
- // return result;
- // }
- // ProductMetadataData productData = getComponentByLabel.left().value();
- // product = convertProductDataToProduct(productData);
- //
- // TitanOperationStatus status = setComponentCreatorFromGraph(product,
- // uniqueId, productNodeType);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- // }
- //
- // status = setComponentLastModifierFromGraph(product, uniqueId,
- // productNodeType);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- //
- // }
- // status = setComponentCategoriesFromGraph(product);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- // }
- //
- // status = setComponentInstancesFromGraph(uniqueId, product,
- // productNodeType, compInstNodeType);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- //
- // }
- //
- // status = setComponentInstancesPropertiesFromGraph(uniqueId, product);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- // }
- //
- // status = setCapabilitiesFromGraph(uniqueId, product,
- // NodeTypeEnum.Product);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- // }
- //
- // status = setRequirementsFromGraph( uniqueId, product,
- // NodeTypeEnum.Product);;
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- // }
- //
- //
- // status = setAllVersions(product);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // result = Either.left(product);
- // return result;
- //
- // } finally {
- // if (false == inTransaction) {
- // if (result == null || result.isRight()) {
- // titanGenericDao.rollback();
- // } else {
- // titanGenericDao.commit();
- // }
- // }
- // }
- // }
-
- private TitanOperationStatus setAllVersions(Product product) {
- Either<Map<String, String>, TitanOperationStatus> res = getVersionList(NodeTypeEnum.Product, product.getVersion(), product, ProductMetadataData.class);
- if (res.isRight()) {
- return res.right().value();
- }
- product.setAllVersions(res.left().value());
- return TitanOperationStatus.OK;
- }
-
- private Either<Product, StorageOperationStatus> sendError(TitanOperationStatus status, StorageOperationStatus statusIfNotFound) {
- Either<Product, StorageOperationStatus> result;
- if (status == TitanOperationStatus.NOT_FOUND) {
- result = Either.right(statusIfNotFound);
- return result;
- } else {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- }
-
- @Override
- TitanOperationStatus setComponentCategoriesFromGraph(Component component) {
- Product product = (Product) component;
- // Building the cat->subcat->grouping triples
- Either<List<ImmutablePair<GroupingData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Product), product.getUniqueId(), GraphEdgeLabels.CATEGORIZED_TO,
- NodeTypeEnum.ProductGrouping, GroupingData.class);
- if (childrenNodes.isRight()) {
- if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("Error when finding groupings for this product, error {}", childrenNodes.right().value());
- return childrenNodes.right().value();
- } else {
- log.debug("No groupings found for this product - this might be normal");
- return TitanOperationStatus.OK;
- }
- }
- Map<CategoryDefinition, Map<SubCategoryDefinition, List<GroupingDefinition>>> categoriesDataStructure = new HashMap<>();
-
- List<ImmutablePair<GroupingData, GraphEdge>> valueList = childrenNodes.left().value();
- for (ImmutablePair<GroupingData, GraphEdge> groupPair : valueList) {
- GroupingData groupingData = groupPair.getLeft();
- Either<ImmutablePair<SubCategoryData, GraphEdge>, TitanOperationStatus> parentSubCat = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ProductGrouping), (String) groupingData.getUniqueId(),
- GraphEdgeLabels.GROUPING, NodeTypeEnum.ProductSubcategory, SubCategoryData.class);
- if (parentSubCat.isRight()) {
- log.debug("Cannot find subcategory for grouping {}", groupingData.getUniqueId());
- return parentSubCat.right().value();
- }
- SubCategoryData subCatData = parentSubCat.left().value().getLeft();
- Either<ImmutablePair<CategoryData, GraphEdge>, TitanOperationStatus> parentCat = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ProductSubcategory), (String) subCatData.getUniqueId(),
- GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ProductCategory, CategoryData.class);
- if (parentCat.isRight()) {
- log.debug("Cannot find category for subcategory {}", subCatData.getUniqueId());
- return parentCat.right().value();
- }
-
- // Building data structure of categories hierarchy
- CategoryDataDefinition categoryDefinition = parentCat.left().value().getLeft().getCategoryDataDefinition();
- SubCategoryDataDefinition subDefinition = subCatData.getSubCategoryDataDefinition();
- GroupingDataDefinition groupingDefinition = groupingData.getGroupingDataDefinition();
-
- CategoryDefinition categoryDef = new CategoryDefinition(categoryDefinition);
- SubCategoryDefinition subDef = new SubCategoryDefinition(subDefinition);
- GroupingDefinition groupingDef = new GroupingDefinition(groupingDefinition);
-
- log.debug("Found category {} -> subcategory {} -> grouping {} for product {}", categoryDefinition.getUniqueId(), subCatData.getUniqueId(), groupingData.getUniqueId(), product.getUniqueId());
- Map<SubCategoryDefinition, List<GroupingDefinition>> subMap = categoriesDataStructure.get(categoryDef);
- if (subMap == null) {
- subMap = new HashMap<>();
- categoriesDataStructure.put(categoryDef, subMap);
- }
- List<GroupingDefinition> groupList = subMap.get(subDef);
- if (groupList == null) {
- groupList = new ArrayList<>();
- subMap.put(subDef, groupList);
- }
- groupList.add(groupingDef);
- }
- convertToCategoriesList(product, categoriesDataStructure);
- return TitanOperationStatus.OK;
- }
-
- private void convertToCategoriesList(Product product, Map<CategoryDefinition, Map<SubCategoryDefinition, List<GroupingDefinition>>> categoriesDataStructure) {
- List<CategoryDefinition> categoryDataList = product.getCategories();
- if (categoryDataList == null) {
- categoryDataList = new ArrayList<CategoryDefinition>();
- }
- for (Entry<CategoryDefinition, Map<SubCategoryDefinition, List<GroupingDefinition>>> triple : categoriesDataStructure.entrySet()) {
- CategoryDefinition categoryDefinition = triple.getKey();
- List<SubCategoryDefinition> subList = new ArrayList<>();
- categoryDefinition.setSubcategories(subList);
- Map<SubCategoryDefinition, List<GroupingDefinition>> value = triple.getValue();
-
- for (Entry<SubCategoryDefinition, List<GroupingDefinition>> pair : value.entrySet()) {
- SubCategoryDefinition subCategoryDefinition = pair.getKey();
- List<GroupingDefinition> list = pair.getValue();
- subList.add(subCategoryDefinition);
- subCategoryDefinition.setGroupings(list);
- }
- categoryDataList.add(categoryDefinition);
- }
- product.setCategories(categoryDataList);
- log.debug("Fetched categories for product {}, categories: {}", product.getUniqueId(), Arrays.toString(categoryDataList.toArray()));
- }
-
- private ProductMetadataData getProductMetadataDataFromProduct(Product product) {
- ProductMetadataData productMetadata = new ProductMetadataData((ProductMetadataDataDefinition) product.getComponentMetadataDefinition().getMetadataDataDefinition());
- return productMetadata;
- }
-
- @Override
- public boolean isComponentExist(String id) {
- return isComponentExist(id, NodeTypeEnum.Product);
- }
-
- // @SuppressWarnings("unchecked")
- // @Override
- // public <T> Either<T, StorageOperationStatus> cloneComponent(T other,
- // String version, boolean inTransaction) {
- // return (Either<T, StorageOperationStatus>) cloneProduct((Product)other,
- // version, inTransaction);
- // }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) cloneProduct((Product) other, version, targetLifecycle, inTransaction);
- }
-
- private Either<Product, StorageOperationStatus> cloneProduct(Product other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) {
- Either<Product, StorageOperationStatus> result = null;
-
- try {
- String origProductId = other.getUniqueId();
- other.setVersion(version);
- other.setUniqueId(null);
-
- Either<Integer, StorageOperationStatus> counterStatus = getComponentInstanceCoutner(origProductId, NodeTypeEnum.Product);
- if (counterStatus.isRight()) {
- StorageOperationStatus status = counterStatus.right().value();
- log.error("failed to get resource instance counter on product {}. status={}", origProductId, counterStatus);
- result = Either.right(status);
- return result;
- }
-
- Either<Product, StorageOperationStatus> createProductMD = createProduct(other, inTransaction);
- if (createProductMD.isRight()) {
- StorageOperationStatus status = createProductMD.right().value();
- log.debug("Failed to clone product. status= {}", status);
- result = Either.right(status);
- return result;
- }
- Product product = createProductMD.left().value();
-
- Either<ImmutablePair<List<ComponentInstance>, Map<String, String>>, StorageOperationStatus> cloneInstances = componentInstanceOperation.cloneAllComponentInstancesFromContainerComponent(origProductId, product,
- NodeTypeEnum.Product, NodeTypeEnum.Service, targetLifecycle, null);
- if (cloneInstances.isRight()) {
- result = Either.right(cloneInstances.right().value());
- return result;
- }
-
- Either<Integer, StorageOperationStatus> setResourceInstanceCounter = setComponentInstanceCounter(product.getUniqueId(), NodeTypeEnum.Product, counterStatus.left().value(), inTransaction);
- if (setResourceInstanceCounter.isRight()) {
- StorageOperationStatus status = setResourceInstanceCounter.right().value();
- log.error("failed to set resource instance counter on product {}. status={}", product.getUniqueId(), setResourceInstanceCounter);
- result = Either.right(status);
- return result;
- }
-
- result = this.getProduct(product.getUniqueId(), inTransaction);
- if (result.isRight()) {
- log.error("Cannot get full product from the graph. status is {}", result.right().value());
- return Either.right(result.right().value());
- }
-
- if (log.isDebugEnabled()) {
- String json = prettyJson.toJson(result.left().value());
- log.debug("Product retrieved is {}", json);
- }
-
- return result;
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- private Either<Product, StorageOperationStatus> getByNamesAndVersion(String nameKey, String nameValue, String version, Map<String, Object> additionalParams, boolean inTransaction) {
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(nameKey, nameValue);
- props.put(GraphPropertiesDictionary.VERSION.getProperty(), version);
- props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Product.getName());
- if (additionalParams != null && !additionalParams.isEmpty()) {
- props.putAll(additionalParams);
- }
-
- Either<List<ProductMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Product, props, ProductMetadataData.class);
-
- if (byCriteria.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value()));
- }
- List<ProductMetadataData> dataList = byCriteria.left().value();
- if (dataList != null && !dataList.isEmpty()) {
- if (dataList.size() > 1) {
- log.debug("More that one instance of product for name {} and version {}", nameValue, version);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- ProductMetadataData productData = dataList.get(0);
- Either<Product, StorageOperationStatus> product = getProduct(productData.getMetadataDataDefinition().getUniqueId(), inTransaction);
- if (product.isRight()) {
- log.debug("Failed to fetch product, name {} id {}", productData.getMetadataDataDefinition().getName(), productData.getMetadataDataDefinition().getUniqueId());
- }
- return product;
- }
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
-
- @Override
- public Product getDefaultComponent() {
- return new Product();
- }
-
- @Override
- protected <T extends org.openecomp.sdc.be.model.Component> StorageOperationStatus updateDerived(org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component currentComponent, ComponentMetadataData componentData,
- Class<T> clazz) {
- log.debug("Derived class isn't supported for product");
- return StorageOperationStatus.OK;
- }
-
- @Override
- public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction) {
- return increaseAndGetComponentInstanceCounter(componentId, NodeTypeEnum.Product, inTransaction);
- }
-
- @Override
- protected StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type) {
- // As agreed with Ella, update categories - delete old and create new
- StorageOperationStatus status = StorageOperationStatus.OK;
- List<CategoryDefinition> newcategories = component.getCategories();
- List<CategoryDefinition> currentcategories = currentComponent.getCategories();
- if (newcategories != null) {
- if (currentcategories != null && !currentcategories.isEmpty()) {
- Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(NodeTypeEnum.ProductGrouping, currentComponent);
- if (findGroupingsForComponent.isRight()) {
- status = findGroupingsForComponent.right().value();
- }
- List<GroupingData> groupingDataToDissociate = findGroupingsForComponent.left().value();
- TitanOperationStatus titanStatus = dissociateCategoriesFromProduct((ProductMetadataData) componentData, groupingDataToDissociate);
- if (titanStatus != TitanOperationStatus.OK) {
- status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
- }
- }
- if (!newcategories.isEmpty()) {
- Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(NodeTypeEnum.ProductGrouping, component);
- if (findGroupingsForComponent.isRight()) {
- status = findGroupingsForComponent.right().value();
- }
- List<GroupingData> groupingDataToAssociate = findGroupingsForComponent.left().value();
- TitanOperationStatus titanStatus = associateCategoriesToProduct((ProductMetadataData) componentData, groupingDataToAssociate);
- if (titanStatus != TitanOperationStatus.OK) {
- status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
- }
- }
- }
- return status;
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public Either<List<Product>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction) {
- return (Either<List<Product>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getFollowedComponent(userId, lifecycleStates, lastStateStates, inTransaction, titanGenericDao, NodeTypeEnum.Product);
- }
-
- @Override
- public Either<Component, StorageOperationStatus> getMetadataComponent(String id, boolean inTransaction) {
- return getMetadataComponent(id, NodeTypeEnum.Product, inTransaction);
- }
-
- @Override
- Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData) {
- return convertProductDataToProduct((ProductMetadataData) componentMetadataData);
- }
-
- @Override
- public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String productName) {
- return validateComponentNameUniqueness(productName, titanGenericDao, NodeTypeEnum.Product);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete, boolean inTransaction) {
- // markComponentToDelete is not defined yet for products
- return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteProduct(componentToDelete.getUniqueId(), inTransaction);
- }
-
- @Override
- public void rollback() {
- titanGenericDao.rollback();
-
- }
-
- @Override
- public void commit() {
- titanGenericDao.commit();
- }
-
- @Override
- public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
- return isComponentInUse(componentId, NodeTypeEnum.Product);
- }
-
- @Override
- public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion() {
- // markForDeletion for products is not implemented yet
- return Either.left(new ArrayList<>());
- }
-
- public Either<Product, StorageOperationStatus> getProductByNameAndVersion(String productName, String productVersion, boolean inTransaction) {
- return getByNamesAndVersion(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normaliseComponentName(productName), productVersion, null, inTransaction);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) getProduct(id, false);
- }
-
- public Either<Product, StorageOperationStatus> updateProduct(Product product, boolean inTransaction, ComponentParametersView filterResultView) {
- return (Either<Product, StorageOperationStatus>) updateComponentFilterResult(product, inTransaction, titanGenericDao, product.getClass(), NodeTypeEnum.Service, filterResultView);
- }
-
- @Override
- protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterResultView) {
- return (Either<T, StorageOperationStatus>) updateProduct((Product) component, inTransaction, filterResultView);
- }
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java
index 9b900b0ae2..6835e813ee 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java
@@ -154,24 +154,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
return functionPatterns;
}
- @Override
- public Either<PropertyDefinition, StorageOperationStatus> getPropertyOfResource(String propertyName, String resourceId) {
-
- String propertyId = UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName);
-
- Either<PropertyData, TitanOperationStatus> getResult = this.titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class);
- if (getResult.isLeft()) {
- PropertyData propertyData = getResult.left().value();
- return Either.left(convertPropertyDataToPropertyDefinition(propertyData, propertyName, resourceId));
- } else {
- TitanOperationStatus titanStatus = getResult.right().value();
- log.debug("Node with id {} was not found in the graph. status: {}", propertyId, titanStatus);
- StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
- return Either.right(storageOperationStatus);
- }
-
- }
-
/*
* (non-Javadoc)
*
@@ -2024,8 +2006,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
}
}
- @Override
- public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition, boolean inTransaction) {
+ private Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition, boolean inTransaction) {
Either<DataTypeDefinition, StorageOperationStatus> result = null;
@@ -2110,8 +2091,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
return getDataTypeByNameWithoutDerived(name, true);
}
- @Override
- public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameWithoutDerived(String name, boolean inTransaction) {
+ private Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameWithoutDerived(String name, boolean inTransaction) {
Either<DataTypeDefinition, StorageOperationStatus> result = null;
try {
@@ -2534,8 +2514,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe
return updateDataType(newDataTypeDefinition, oldDataTypeDefinition, true);
}
- @Override
- public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition, boolean inTransaction) {
+ private Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition, boolean inTransaction) {
Either<DataTypeDefinition, StorageOperationStatus> result = null;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java
deleted file mode 100644
index a2fe3d61d3..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java
+++ /dev/null
@@ -1,1419 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import com.thinkaurelius.titan.core.TitanTransaction;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
-import org.openecomp.sdc.be.model.CapabiltyInstance;
-import org.openecomp.sdc.be.model.Point;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.RequirementImplDef;
-import org.openecomp.sdc.be.model.operations.api.IRequirementOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.resources.data.CapabilityData;
-import org.openecomp.sdc.be.resources.data.CapabilityInstData;
-import org.openecomp.sdc.be.resources.data.CapabilityTypeData;
-import org.openecomp.sdc.be.resources.data.PropertyValueData;
-import org.openecomp.sdc.be.resources.data.RequirementData;
-import org.openecomp.sdc.be.resources.data.RequirementImplData;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.openecomp.sdc.be.resources.data.UniqueIdData;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-
-import fj.data.Either;
-
-@Component("requirement-operation")
-public class RequirementOperation implements IRequirementOperation {
-
- private static final String NA = "NA";
-
- private static final String EQUAL_SIGN = "=";
-
- private static final String EMPTY_STRING = "";
-
- public RequirementOperation() {
- super();
- }
-
- private static Logger log = LoggerFactory.getLogger(RequirementOperation.class.getName());
-
- @javax.annotation.Resource
- private CapabilityOperation capabilityOperation;
-
- @javax.annotation.Resource
- private CapabilityTypeOperation capabilityTypeOperation;
-
- @javax.annotation.Resource
- private TitanGenericDao titanGenericDao;
-
- /**
- * FOR TEST ONLY
- *
- * @param titanGenericDao
- */
- public void setTitanGenericDao(TitanGenericDao titanGenericDao) {
- this.titanGenericDao = titanGenericDao;
- }
-
- protected CapabilityTypeDefinition convertCTDataToCTDefinition(CapabilityTypeData capabilityTypeData) {
- log.debug("The object returned after create capability is {}", capabilityTypeData);
-
- CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition(capabilityTypeData.getCapabilityTypeDataDefinition());
-
- return capabilityTypeDefResult;
- }
-
- /**
- * FOR TEST ONLY
- *
- * @param capabilityOperation
- */
- public void setCapabilityOperation(CapabilityOperation capabilityOperation) {
- this.capabilityOperation = capabilityOperation;
- }
-
- public void setCapabilityTypeOperation(CapabilityTypeOperation capabilityTypeOperation) {
- this.capabilityTypeOperation = capabilityTypeOperation;
- }
-
- @Override
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId) {
-
- return addRequirementToResource(reqName, reqDefinition, resourceId, false);
- }
-
- private Either<GraphRelation, TitanOperationStatus> associateRequirementToRelationshipType(RequirementData reqData, RequirementDefinition reqDefinition) {
-
- String relationship = reqDefinition.getRelationship();
-
- if (relationship == null) {
- log.debug("The provided relationship is null.");
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
- UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.RelationshipType, relationship);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqData, uniqueIdData, GraphEdgeLabels.RELATIONSHIP_TYPE, null);
-
- return createRelation;
-
- }
-
- /**
- * Associate the requirement node to its capability type
- *
- * @param reqData
- * @param reqDefinition
- * @return
- */
- private Either<GraphRelation, TitanOperationStatus> associateRequirementToCapabilityType(RequirementData reqData, RequirementDefinition reqDefinition) {
-
- String capability = reqDefinition.getCapability();
-
- UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.CapabilityType, capability);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqData, uniqueIdData, GraphEdgeLabels.CAPABILITY_TYPE, null);
-
- log.debug("After associating requirementData {} to capability {}. status is {}", reqData, capability, createRelation);
-
- return createRelation;
- }
-
- private TitanOperationStatus associateRequirementToCapabilityType(TitanVertex reqData, RequirementDefinition reqDefinition) {
-
- String capability = reqDefinition.getCapability();
-
- UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.CapabilityType, capability);
- TitanOperationStatus createRelation = titanGenericDao.createEdge(reqData, uniqueIdData, GraphEdgeLabels.CAPABILITY_TYPE, null);
-
- log.debug("After associating requirementData {} to capability {}. status is {}", reqData, capability, createRelation);
-
- return createRelation;
- }
-
- /**
- * Associate requirement impl node to capability instance node
- *
- * @param reqImplData
- * @param capabilityInstData
- * @param capabilityName
- * @return
- */
- private Either<GraphRelation, TitanOperationStatus> associateRequirementImplToCapabilityInst(RequirementImplData reqImplData, CapabilityInstData capabilityInstData, String capabilityName) {
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName);
-
- log.debug("Before associating requirement impl {} to capability instance {}", reqImplData, capabilityInstData);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqImplData, capabilityInstData, GraphEdgeLabels.CAPABILITY_INST, props);
- log.debug("After associating requirement impl {} to capability instance {}.status is {}", reqImplData, capabilityInstData, createRelation);
-
- return createRelation;
-
- }
-
- /**
- * Add requirement node to graph
- *
- * @param resourceId
- * @param reqName
- * @param reqDefinition
- * @return
- */
- private Either<RequirementData, TitanOperationStatus> addRequirementData(String resourceId, String reqName, RequirementDefinition reqDefinition) {
-
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(resourceId);
-
- RequirementData requirementData = buildRequirementData(resourceId, reqName, reqDefinition);
-
- log.debug("Before adding requirement data to graph {}", requirementData);
- Either<RequirementData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(requirementData, RequirementData.class);
-
- log.debug("After adding requirement to graph {}", requirementData);
- if (createNodeResult.isRight()) {
- TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add requirement {} [{}] to graph. status is {}", reqName, requirementData, operationStatus);
- return Either.right(operationStatus);
- }
-
- TitanOperationStatus status = associateResourceDataToRequirementData(resourceId, reqName, resourceData, requirementData);
- if (status != TitanOperationStatus.OK) {
- return Either.right(status);
- }
-
- return Either.left(createNodeResult.left().value());
-
- }
-
- private Either<TitanVertex, TitanOperationStatus> addRequirementData(TitanVertex vertex, String resourceId, String reqName, RequirementDefinition reqDefinition) {
-
- RequirementData requirementData = buildRequirementData(resourceId, reqName, reqDefinition);
-
- log.debug("Before adding requirement data to graph {}", requirementData);
- Either<TitanVertex, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(requirementData);
-
- log.debug("After adding requirement to graph {}", requirementData);
- if (createNodeResult.isRight()) {
- TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add requirement {} [{}] to graph. status is {}", reqName, requirementData, operationStatus);
- return Either.right(operationStatus);
- }
-
- TitanOperationStatus status = associateResourceDataToRequirementData(resourceId, reqName, vertex, createNodeResult.left().value());
- if (!status.equals(TitanOperationStatus.OK)) {
- return Either.right(status);
- }
- return Either.left(createNodeResult.left().value());
- }
-
- /**
- * Asssociate resource node to requirement node with REQUIREMENT label and requirement name as property on the edge.
- *
- * @param resourceId
- * @param reqName
- * @param resourceData
- * @param requirementData
- * @return
- */
- private TitanOperationStatus associateResourceDataToRequirementData(String resourceId, String reqName, ResourceMetadataData resourceData, RequirementData requirementData) {
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), reqName);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceData, requirementData, GraphEdgeLabels.REQUIREMENT, props);
- log.debug("After creatin edge between resource {} to requirement {}", resourceId, requirementData);
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate resource {} to requirement {} [ {} ] in graph. status is {}", resourceId, reqName, requirementData, operationStatus);
- }
- return TitanOperationStatus.OK;
- }
-
- private TitanOperationStatus associateResourceDataToRequirementData(String resourceId, String reqName, TitanVertex resourceVertex, TitanVertex requirementVertex) {
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), reqName);
- TitanOperationStatus createRelResult = titanGenericDao.createEdge(resourceVertex, requirementVertex, GraphEdgeLabels.REQUIREMENT, props);
- log.debug("After creatin edge between resource {} to requirement {}", resourceId, requirementVertex);
- if (!createRelResult.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate resource {} to requirement {} in graph. status is {}", resourceId, reqName, createRelResult);
- }
- return TitanOperationStatus.OK;
- }
-
- private RequirementData buildRequirementData(String resourceId, String reqName, RequirementDefinition reqDefinition) {
-
- RequirementData requirementData = new RequirementData();
- requirementData.setNode(reqDefinition.getNode());
- requirementData.setUniqueId(UniqueIdBuilder.buildRequirementUid(resourceId, reqName));
- Long creationTime = System.currentTimeMillis();
- requirementData.setCreationTime(creationTime);
- requirementData.setModificationTime(creationTime);
- requirementData.setRelationshipType(reqDefinition.getRelationship());
- requirementData.setMinOccurrences(reqDefinition.getMinOccurrences());
- requirementData.setMaxOccurrences(reqDefinition.getMaxOccurrences());
-
- return requirementData;
- }
-
- /**
- * build requirement impl node associate it to resource, requirement & implementation resource
- *
- * [RESOURCE] --> [REQUIREMENT IMPL] --> [ RESOURCE IMPL ] | V [REQUIREMENT]
- *
- * @param resourceLabel
- * @param resourceId
- * @param reqName
- * @param requirementUid
- * @param reqImplDefinition
- * @return
- */
- private Either<RequirementImplData, TitanOperationStatus> addRequirementImplData(NodeTypeEnum resourceLabel, String resourceId, String reqName, String requirementUid, RequirementImplDef reqImplDefinition) {
-
- RequirementImplData requirementImplData = buildRequirementImplData(resourceId, reqName, reqImplDefinition);
-
- log.debug("Before adding requirement impl data to graph {}", requirementImplData);
- Either<RequirementImplData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(requirementImplData, RequirementImplData.class);
- log.debug("After adding requirement to graph {}. status is {}", requirementImplData, createNodeResult);
- if (createNodeResult.isRight()) {
- TitanOperationStatus operationStatus = createNodeResult.right().value();
- log.error("Failed to add requirement {} [ {} ] to graph. status is {}", reqName, requirementImplData, operationStatus);
- return Either.right(operationStatus);
- }
-
- Either<GraphRelation, TitanOperationStatus> createRelResult = associateReqImplRoResource(resourceLabel, resourceId, reqName, requirementImplData);
- if (createRelResult.isRight()) {
- TitanOperationStatus operationStatus = createRelResult.right().value();
- log.error("Failed to associate resource {} to requirement impl {} [ {} ] in graph. status is {}", resourceId, requirementImplData, requirementImplData, operationStatus);
- return Either.right(operationStatus);
- }
-
- Either<GraphRelation, TitanOperationStatus> associateToResourceImpl = associateReqImplToImplResource(requirementImplData, reqImplDefinition.getNodeId());
- if (associateToResourceImpl.isRight()) {
- TitanOperationStatus operationStatus = associateToResourceImpl.right().value();
- log.error("Failed to associate requirement impl {} to resource impl {} [ {} ] in graph. status is {}", requirementImplData, reqImplDefinition.getNodeId(), requirementImplData, operationStatus);
- return Either.right(operationStatus);
- }
-
- Either<GraphRelation, TitanOperationStatus> associateToRequirement = associateReqImplToRequirement(requirementImplData, requirementUid);
- if (associateToRequirement.isRight()) {
- TitanOperationStatus operationStatus = associateToRequirement.right().value();
- log.error("Failed to associate requirement impl {} to requirement {} in graph. status is {}", requirementImplData, reqName, operationStatus);
- return Either.right(operationStatus);
- }
-
- return Either.left(createNodeResult.left().value());
-
- }
-
- private RequirementImplData buildRequirementImplData(String resourceId, String reqName, RequirementImplDef reqImplDefinition) {
- String reqImplUid = UniqueIdBuilder.buildRequirementImplUid(resourceId, reqName);
- RequirementImplData requirementImplData = new RequirementImplData();
- requirementImplData.setName(reqName);
- requirementImplData.setUniqueId(reqImplUid);
- Long creationTime = System.currentTimeMillis();
- requirementImplData.setCreationTime(creationTime);
- requirementImplData.setModificationTime(creationTime);
- Point point = reqImplDefinition.getPoint();
- if (point != null) {
- requirementImplData.setPosX(point.getX());
- requirementImplData.setPosY(point.getY());
- }
- return requirementImplData;
- }
-
- /**
- * associate requirement impl node to the source requirement. The source requirement maybe belongs to one of parents.
- *
- * @param requirementImplData
- * @param requirementUid
- * @return
- */
- private Either<GraphRelation, TitanOperationStatus> associateReqImplToRequirement(RequirementImplData requirementImplData, String requirementUid) {
-
- UniqueIdData to = new UniqueIdData(NodeTypeEnum.Requirement, requirementUid);
- log.debug("Before creating edge between requirement impl {} to requirement {}", requirementImplData, requirementUid);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(requirementImplData, to, GraphEdgeLabels.IMPLEMENTATION_OF, null);
- log.debug("Before creating edge between requirement impl {} to requirement {}. status is {}", requirementImplData, requirementUid, createRelResult);
-
- return createRelResult;
- }
-
- /**
- * Associate requirement impl node to the node which supply this requirement.
- *
- * @param requirementImplData
- * @param nodeId
- * @return
- */
- private Either<GraphRelation, TitanOperationStatus> associateReqImplToImplResource(RequirementImplData requirementImplData, String nodeId) {
-
- UniqueIdData nodeImpl = new UniqueIdData(NodeTypeEnum.Resource, nodeId);
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), nodeId);
- log.debug("Before creating edge between requirement impl {} to node impl {}", requirementImplData, nodeId);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(requirementImplData, nodeImpl, GraphEdgeLabels.NODE_IMPL, props);
- log.debug("After creating edge between requirement {} to node impl {}. status is {}", requirementImplData, nodeId, createRelResult);
-
- return createRelResult;
- }
-
- /**
- * create an edge between the requirement impl node to the implementation resource.
- *
- * @param resourceLabel
- * @param resourceId
- * @param reqName
- * @param requirementImplData
- * @return
- */
- private Either<GraphRelation, TitanOperationStatus> associateReqImplRoResource(NodeTypeEnum resourceLabel, String resourceId, String reqName, RequirementImplData requirementImplData) {
-
- UniqueIdData resource = new UniqueIdData(resourceLabel, resourceId);
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), reqName);
- log.debug("Before creating edge between resource {} to requirement impl {}", resourceId, requirementImplData);
- Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resource, requirementImplData, GraphEdgeLabels.REQUIREMENT_IMPL, props);
- log.debug("After creating edge between to requirement impl {} to resource {}. status is {}", requirementImplData, resource, createRelResult);
-
- return createRelResult;
- }
-
- private void validateNodeExists(String node) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction) {
-
- Either<RequirementDefinition, StorageOperationStatus> result = null;
- try {
-
- log.debug("Going to add requirement {} to resource {}. requirement definition is {}", reqName, resourceId, reqDefinition);
-
- validateNodeExists(reqDefinition.getNode());
-
- // 1. add requirement node in graph and associate it to the resource
- log.debug("Going to add requirement node in graph and associate it to the resource");
- Either<RequirementData, TitanOperationStatus> addRequirementData = addRequirementData(resourceId, reqName, reqDefinition);
- if (addRequirementData.isRight()) {
- log.error("Failed to add requirement {} node to graph. status is {}", reqName, addRequirementData);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addRequirementData.right().value()));
- return result;
- }
-
- RequirementData requirementData = addRequirementData.left().value();
-
- log.debug("Going to associate the requirement to the appriopriate capability type");
- Either<GraphRelation, TitanOperationStatus> associateReqToCapabilityType = associateRequirementToCapabilityType(requirementData, reqDefinition);
- if (associateReqToCapabilityType.isRight()) {
- log.error("Failed to associate requirement data node {} to the capability type node {}", requirementData, reqDefinition.getCapability());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateReqToCapabilityType.right().value()));
- return result;
- }
-
- // TODO: esofer associate requirement to the relationship type
- /*
- * Either<GraphRelation, TitanOperationStatus> associateReqToRelshipType = associateRequirementToRelationshipType( requirementData, reqDefinition);
- *
- * if (associateReqToRelshipType.isRight() && associateReqToRelshipType.right().value() != TitanOperationStatus.NOT_FOUND) { log.error("Failed to associate requirement data node " + requirementData + " to the relationship type node " +
- * reqDefinition.getRelationship()); result = Either .right(TitanStatusConverter .convertTitanStatusToStorageStatus(associateReqToRelshipType .right().value())); return result; }
- */
-
- log.debug("Going to fetch the requirement {} from graph", reqName);
- Either<RequirementDefinition, TitanOperationStatus> requirementDefinitionRes = getRequirement(requirementData.getUniqueId());
- if (requirementDefinitionRes.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(requirementDefinitionRes.right().value()));
- return result;
- }
-
- result = Either.left(requirementDefinitionRes.left().value());
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public StorageOperationStatus addRequirementToResource(TitanVertex metadataVertex, String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction) {
-
- StorageOperationStatus result = StorageOperationStatus.OK;
- try {
-
- log.debug("Going to add requirement {} to resource . requirement definition is ", reqName, resourceId, reqDefinition);
-
- validateNodeExists(reqDefinition.getNode());
-
- // 1. add requirement node in graph and associate it to the resource
- log.debug("Going to add requirement node in graph and associate it to the resource");
- Either<TitanVertex, TitanOperationStatus> addRequirementData = addRequirementData(metadataVertex, resourceId, reqName, reqDefinition);
- if (addRequirementData.isRight()) {
- log.error("Failed to add requirement {} node to graph. status is {}", reqName, addRequirementData.right().value());
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(addRequirementData.right().value());
- return result;
- }
-
- log.debug("Going to associate the requirement to the appriopriate capability type");
- TitanOperationStatus associateReqToCapabilityType = associateRequirementToCapabilityType(addRequirementData.left().value(), reqDefinition);
- if (!associateReqToCapabilityType.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate requirement data node {} to the capability type node {}", reqDefinition.getCapability(), reqDefinition);
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(associateReqToCapabilityType);
- return result;
- }
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || !result.equals(TitanOperationStatus.OK)) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- /**
- * Fetch requirement from graph
- *
- * @param uniqueId
- * - the uniqueid of the requirement in the graph
- * @return
- */
- public Either<RequirementDefinition, TitanOperationStatus> getRequirement(String uniqueId) {
-
- log.debug("Going to fetch the requirement {} from graph.", uniqueId);
- Either<RequirementData, TitanOperationStatus> reqDataResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), uniqueId, RequirementData.class);
-
- if (reqDataResult.isRight()) {
- log.error("Failed to find requirement node in graph {}. status is {}", uniqueId, reqDataResult);
- return Either.right(reqDataResult.right().value());
- }
-
- log.debug("Going to fetch the capability type associate to requirement {}", uniqueId);
- Either<ImmutablePair<CapabilityTypeData, GraphEdge>, TitanOperationStatus> capabilityTypeRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.CAPABILITY_TYPE, NodeTypeEnum.CapabilityType,
- CapabilityTypeData.class);
-
- if (capabilityTypeRes.isRight()) {
- log.error("Cannot find the capability of a given requirement {}. status is {}", uniqueId, capabilityTypeRes);
- return Either.right(capabilityTypeRes.right().value());
- }
-
- ImmutablePair<CapabilityTypeData, GraphEdge> capability = capabilityTypeRes.left().value();
-
- String capabilityType = capability.getKey().getCapabilityTypeDataDefinition().getType();
-
- // TODO: esofer add relationship as edge
- /*
- * Either<List<ImmutablePair<RelationshipTypeData, GraphEdge>>, TitanOperationStatus> relationshipRes = titanGenericDao .getChildrenNodes( GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.RELATIONSHIP_TYPE,
- * NodeTypeEnum.RelationshipType, RelationshipTypeData.class);
- *
- * if (relationshipRes.isRight() && relationshipRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- * return Either.right(relationshipRes.right().value()); }
- *
- * String relationshipType = null; if (relationshipRes.isLeft()) { List<ImmutablePair<RelationshipTypeData, GraphEdge>> rstPairs = relationshipRes .left().value(); if (rstPairs == null || true == rstPairs.isEmpty()) { log.error(
- * "Cannot find the capability of a given requirement " + uniqueId); return Either.right(TitanOperationStatus.NOT_FOUND); }
- *
- * ImmutablePair<RelationshipTypeData, GraphEdge> relationship = rstPairs .get(0); relationshipType = relationship.getKey().getType(); }
- */
-
- log.debug("Going to fetch the capability type associate to requirement {}", uniqueId);
- Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.REQUIREMENT, NodeTypeEnum.Resource,
- ResourceMetadataData.class);
- if (parentNode.isRight()) {
- log.error("Cannot find the parent resource for a given requirement {}. status is {}", uniqueId, parentNode.right().value());
- return Either.right(parentNode.right().value());
- }
-
- RequirementData requirementData = reqDataResult.left().value();
-
- RequirementDefinition requirementDefinition = new RequirementDefinition();
- requirementDefinition.setOwnerId(parentNode.left().value().getLeft().getMetadataDataDefinition().getUniqueId());
- requirementDefinition.setNode(requirementData.getNode());
- requirementDefinition.setUniqueId(requirementData.getUniqueId());
- requirementDefinition.setCapability(capabilityType);
- requirementDefinition.setRelationship(requirementData.getRelationshipType());
- requirementDefinition.setMinOccurrences(requirementData.getMinOccurrences());
- requirementDefinition.setMaxOccurrences(requirementData.getMaxOccurrences());
-
- return Either.left(requirementDefinition);
-
- }
-
- @Override
- public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, String resourceId) {
-
- return getRequirementOfResource(reqName, resourceId, false);
- }
-
- @Override
- public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, String resourceId, boolean inTransaction) {
-
- Either<RequirementDefinition, StorageOperationStatus> result = null;
-
- try {
- String reqUniqueId = UniqueIdBuilder.buildRequirementUid(resourceId, reqName);
- Either<RequirementDefinition, TitanOperationStatus> requirementRes = getRequirement(reqUniqueId);
-
- if (requirementRes.isRight()) {
- log.debug("Failed to retrieve requirement {} associated to resource {}", reqName, resourceId);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(requirementRes.right().value()));
- } else {
- result = Either.left(requirementRes.left().value());
- }
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId) {
-
- return addRequirementImplToResource(reqName, reqDefinition, resourceId, parentReqUniqueId, false);
-
- }
-
- @Override
- public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, RequirementImplDef reqImplDefinition, String resourceId, String parentReqUniqueId, boolean inTransaction) {
-
- Either<RequirementDefinition, StorageOperationStatus> result = null;
-
- try {
-
- // find the requirement defined at the resource itself or under one
- // of its parents
- Either<RequirementDefinition, TitanOperationStatus> findReq = getRequirement(parentReqUniqueId);
- log.debug("After looking for requirement {}. status is {}", parentReqUniqueId, findReq);
- if (findReq.isRight()) {
- TitanOperationStatus status = findReq.right().value();
- log.error("The requirment {} was not found in the graph. status is {}", parentReqUniqueId, findReq.right().value());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- RequirementDefinition reqDefinition = findReq.left().value();
- String reqNode = reqDefinition.getNode();
- String reqCapability = reqDefinition.getCapability();
-
- String nodeIdImpl = reqImplDefinition.getNodeId();
-
- checkNodeIdImplementsRequirementNode(nodeIdImpl, reqNode);
-
- Either<RequirementImplData, TitanOperationStatus> addRequirementImplData = addRequirementImplData(NodeTypeEnum.Resource, resourceId, reqName, parentReqUniqueId, reqImplDefinition);
-
- if (addRequirementImplData.isRight()) {
- TitanOperationStatus status = addRequirementImplData.right().value();
- log.error("Failed to add requirement data impl node in the graph. status is {}", addRequirementImplData.right().value());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- RequirementImplData requirementImplData = addRequirementImplData.left().value();
-
- log.debug("Add the properties of the capabilities of the target node {} to the requirement impl node {} in graph.", nodeIdImpl, requirementImplData.getUniqueId());
- Map<String, CapabiltyInstance> requirementPropertiesPerCapability = reqImplDefinition.getRequirementProperties();
- TitanOperationStatus addPropsResult = addCapabilityPropertiesToReqImpl(requirementImplData, reqCapability, nodeIdImpl, requirementPropertiesPerCapability);
-
- if (addPropsResult != TitanOperationStatus.OK) {
- log.error("Failed to add capabilities properties to Requirement impl {}", requirementImplData);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropsResult));
- return result;
- }
-
- result = Either.left(reqDefinition);
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- return result;
- }
-
- private Either<RequirementImplDef, TitanOperationStatus> getRequirementImplOfResource(String reqName, String resourceId) {
-
- RequirementImplDef requirementImplDef = new RequirementImplDef();
-
- Either<List<ImmutablePair<RequirementImplData, GraphEdge>>, TitanOperationStatus> reqImplNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.REQUIREMENT_IMPL,
- NodeTypeEnum.RequirementImpl, RequirementImplData.class);
- log.debug("After looking for requirement impl edge of resource {}", resourceId);
- if (reqImplNodesRes.isRight()) {
- TitanOperationStatus status = reqImplNodesRes.right().value();
- return Either.right(status);
- }
-
- boolean found = false;
- List<ImmutablePair<RequirementImplData, GraphEdge>> reqImplNodes = reqImplNodesRes.left().value();
- for (ImmutablePair<RequirementImplData, GraphEdge> entry : reqImplNodes) {
- GraphEdge graphEdge = entry.getValue();
- String edgeType = (String) graphEdge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty());
- if (reqName.equals(edgeType)) {
- found = true;
- RequirementImplData requirementImplData = entry.getKey();
-
- requirementImplDef.setUniqueId(requirementImplData.getUniqueId());
-
- Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> nodeImplRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RequirementImpl), requirementImplData.getUniqueId(),
- GraphEdgeLabels.NODE_IMPL, NodeTypeEnum.Resource, ResourceMetadataData.class);
-
- if (nodeImplRes.isRight()) {
- TitanOperationStatus status = nodeImplRes.right().value();
- log.debug("No implementation resource was found under requirement impl {}. status is {}", requirementImplData.getUniqueId(), status);
-
- return Either.right(status);
- }
- String nodeImpl = nodeImplRes.left().value().getKey().getMetadataDataDefinition().getUniqueId();
- requirementImplDef.setNodeId(nodeImpl);
-
- String posX = requirementImplData.getPosX();
- String posY = requirementImplData.getPosY();
- if (posX != null && posY != null) {
- Point point = new Point(posX, posY);
- requirementImplDef.setPoint(point);
- }
-
- Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> capaInstDataRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RequirementImpl), requirementImplData.getUniqueId(),
- GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class);
- if (capaInstDataRes.isRight()) {
- TitanOperationStatus status = capaInstDataRes.right().value();
- log.debug("No capability instance was found under requirement impl {}. status is {}", requirementImplData.getUniqueId(), status);
-
- return Either.right(status);
- }
-
- Map<String, CapabiltyInstance> requirementProperties = new HashMap<String, CapabiltyInstance>();
-
- List<ImmutablePair<CapabilityInstData, GraphEdge>> list = capaInstDataRes.left().value();
- for (ImmutablePair<CapabilityInstData, GraphEdge> capabilityInst : list) {
- CapabilityInstData capabilityInstData = capabilityInst.getKey();
- GraphEdge edge = capabilityInst.getValue();
- Map<String, Object> properties = edge.getProperties();
- if (properties == null) {
- log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), edge);
- return Either.right(TitanOperationStatus.INVALID_ELEMENT);
- }
- String capabilityName = (String) properties.get(GraphPropertiesDictionary.NAME.getProperty());
- if (capabilityName == null) {
- log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), edge);
- return Either.right(TitanOperationStatus.INVALID_ELEMENT);
- }
-
- // List<String> keyValuePropertiesList = capabilityInstData
- // .getProperties();
- // Map<String, String> actualValues = new HashMap<String,
- // String>();
- // fillMapFromKeyValueList(keyValuePropertiesList,
- // actualValues);
- CapabiltyInstance capabiltyInstance = new CapabiltyInstance();
- capabiltyInstance.setUniqueId(capabilityInstData.getUniqueId());
- // capabiltyInstance.setProperties(actualValues);
- requirementProperties.put(capabilityName, capabiltyInstance);
-
- Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> propertyValueNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst),
- capabilityInstData.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class);
-
- if (propertyValueNodesRes.isRight()) {
- TitanOperationStatus status = propertyValueNodesRes.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find the property values of capability instance {}. status is {}", capabilityInstData, status);
- return Either.right(status);
- }
- } else {
- List<ImmutablePair<PropertyValueData, GraphEdge>> propertyValueNodes = propertyValueNodesRes.left().value();
-
- if (propertyValueNodes != null) {
-
- Map<String, String> actualValues = new HashMap<String, String>();
- TitanOperationStatus fillPropertiesResult = fillPropertiesMapFromNodes(propertyValueNodes, actualValues);
-
- if (fillPropertiesResult != TitanOperationStatus.OK) {
- log.error("Failed to fetch properties of capability {}", capabilityName);
- return Either.right(fillPropertiesResult);
- }
-
- if (false == actualValues.isEmpty()) {
- capabiltyInstance.setProperties(actualValues);
- }
- }
- }
-
- }
-
- requirementImplDef.setRequirementProperties(requirementProperties);
-
- break;
- } else {
- continue;
- }
- }
-
- if (false == found) {
- log.debug("Cannot find requirement impl under resource {}", resourceId);
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- return Either.left(requirementImplDef);
- }
-
- private void fillMapFromKeyValueList(List<String> keyValuePropertiesList, Map<String, String> actualValues) {
-
- if (keyValuePropertiesList != null) {
- for (String keyValue : keyValuePropertiesList) {
- int equalSignLocation = keyValue.indexOf(EQUAL_SIGN);
- if (equalSignLocation > -1) {
- String key = keyValue.substring(0, equalSignLocation);
- String value = EMPTY_STRING;
- if (equalSignLocation + 1 < keyValue.length()) {
- value = keyValue.substring(equalSignLocation + 1);
- }
- actualValues.put(key, value);
- }
- }
- }
-
- }
-
- private TitanOperationStatus fillPropertiesMapFromNodes(List<ImmutablePair<PropertyValueData, GraphEdge>> propertyValueNodes, Map<String, String> actualValues) {
- if (propertyValueNodes != null) {
- for (ImmutablePair<PropertyValueData, GraphEdge> propertyValuePair : propertyValueNodes) {
- PropertyValueData propertyValueData = propertyValuePair.getKey();
- GraphEdge propertyValueEdge = propertyValuePair.getValue();
- Map<String, Object> propertyEdgeProps = propertyValueEdge.getProperties();
- if (propertyEdgeProps == null) {
- log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), propertyValueEdge);
- return TitanOperationStatus.INVALID_ELEMENT;
- }
- String paramName = (String) propertyEdgeProps.get(GraphPropertiesDictionary.NAME.getProperty());
- if (paramName == null) {
- log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), propertyValueEdge);
- return TitanOperationStatus.INVALID_ELEMENT;
- }
- actualValues.put(paramName, propertyValueData.getValue());
- }
- }
- return TitanOperationStatus.OK;
- }
-
- private TitanOperationStatus addCapabilityPropertiesToReqImpl(RequirementImplData reqImplData, String reqCapability, String nodeIdImpl, Map<String, CapabiltyInstance> propertiesValuePerCapability) {
-
- TitanOperationStatus result = null;
-
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> allCapabilities = capabilityOperation.getAllCapabilitiesPairs(nodeIdImpl);
- log.trace("Atter looking for the capabilities of resource {}. result is {}", nodeIdImpl, allCapabilities);
- if (allCapabilities.isRight()) {
- TitanOperationStatus status = allCapabilities.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to find capabilities of resource {}. status is {}", nodeIdImpl, status);
- return status;
- }
- } else {
-
- List<ImmutablePair<CapabilityData, GraphEdge>> capabilitiesValue = allCapabilities.left().value();
- checkImplNodeContainsReqCapability(reqCapability, capabilitiesValue);
-
- for (ImmutablePair<CapabilityData, GraphEdge> entry : capabilitiesValue) {
-
- CapabilityData capabilityData = entry.getKey();
-
- GraphEdge graphEdge = entry.getValue();
-
- Either<String, TitanOperationStatus> capabilityNameResult = findCapabilityName(capabilityData, graphEdge);
-
- if (capabilityNameResult.isRight()) {
- TitanOperationStatus status = capabilityNameResult.right().value();
- log.error("Failed to find capability name from the edge associated to capability {}", capabilityData);
- return status;
- }
-
- String capabilityName = capabilityNameResult.left().value();
- log.debug("Going to set properties of capability {}", capabilityName);
- String cabilityDataUid = capabilityData.getUniqueId();
-
- Either<CapabilityTypeData, TitanOperationStatus> ctDataResult = capabilityOperation.getCapabilityTypeOfCapability(cabilityDataUid);
-
- if (ctDataResult.isRight()) {
- log.error("Cannot find capability type of capbility {}. status is {}", cabilityDataUid, ctDataResult);
- TitanOperationStatus status = ctDataResult.right().value();
- return status;
- }
-
- CapabilityTypeData capabilityTypeData = ctDataResult.left().value();
-
- Either<Map<String, PropertyDefinition>, TitanOperationStatus> propertiesStatus = findPropertiesOfCapability(capabilityTypeData);
- if (propertiesStatus.isRight()) {
- TitanOperationStatus status = propertiesStatus.right().value();
- log.error("Failed to fetch properties definitions from capability. status is {}", status);
- return status;
- }
-
- Map<String, PropertyDefinition> properties = propertiesStatus.left().value();
-
- CapabiltyInstance capabiltyInstance = null;
- if (propertiesValuePerCapability != null) {
- capabiltyInstance = propertiesValuePerCapability.get(capabilityName);
- }
-
- Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceNode = createCapabilityInstanceNode(capabilityName, reqImplData);
- if (createCapabilityInstanceNode.isRight()) {
- TitanOperationStatus status = createCapabilityInstanceNode.right().value();
- log.error("Failed to create capability instance node ({}) in graph. status is {}", capabilityName, status);
-
- return status;
- }
- CapabilityInstData capabilityInstData = createCapabilityInstanceNode.left().value();
-
- Either<List<GraphRelation>, TitanOperationStatus> instanceProperties = addPropertiesToCapabilityInstance(properties, capabiltyInstance, capabilityInstData);
-
- if (instanceProperties.isRight()) {
- TitanOperationStatus status = instanceProperties.right().value();
- log.debug("Failed to add properties to capability instance. status is {}", status);
- return status;
- }
-
- Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToCapabilityType = associateCapabilityInstToCapabilityType(capabilityInstData, capabilityTypeData);
- if (associateCapabilityInstToCapabilityType.isRight()) {
- TitanOperationStatus status = associateCapabilityInstToCapabilityType.right().value();
- log.error("Failed to associate capability instance {} to capability type node {} in graph. status is {}", capabilityInstData, capabilityTypeData, status);
-
- return status;
- }
-
- Either<GraphRelation, TitanOperationStatus> associateCapabilityInst = associateRequirementImplToCapabilityInst(reqImplData, capabilityInstData, capabilityName);
- if (associateCapabilityInst.isRight()) {
- TitanOperationStatus status = associateCapabilityInst.right().value();
- log.error("Failed to associate requirement impl {} to capability instance node {} of capability {}) in graph. status is {}", reqImplData, capabilityInstData, capabilityName, status);
-
- return status;
- }
-
- }
- result = TitanOperationStatus.OK;
- }
- return result;
- }
-
- private Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfCapability(CapabilityTypeData capabilityTypeData) {
- String capabilityTypeUid = capabilityTypeData.getUniqueId();
-
- Either<CapabilityTypeDefinition, TitanOperationStatus> capabilityTypeResult = capabilityTypeOperation.getCapabilityTypeByUid(capabilityTypeUid);
-
- if (capabilityTypeResult.isRight()) {
- log.error("Failed to find capabilityType {} in the graph. status is {}", capabilityTypeUid, capabilityTypeResult);
- return Either.right(capabilityTypeResult.right().value());
- }
-
- CapabilityTypeDefinition capabilityTypeDef = capabilityTypeResult.left().value();
- Map<String, PropertyDefinition> properties = capabilityTypeDef.getProperties();
-
- return Either.left(properties);
- }
-
- private Either<String, TitanOperationStatus> findCapabilityName(CapabilityData capabilityData, GraphEdge graphEdge) {
- Map<String, Object> edgeProps = graphEdge.getProperties();
- String capabilityName = (String) edgeProps.get(GraphPropertiesDictionary.NAME.getProperty());
-
- if (capabilityName == null) {
- log.debug("Cannot find the name of the capability associated to node {}", capabilityData);
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
- return Either.left(capabilityName);
- }
-
- private Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToCapabilityType(CapabilityInstData capabilityInstData, CapabilityTypeData capabilityTypeData) {
-
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(capabilityInstData, capabilityTypeData, GraphEdgeLabels.INSTANCE_OF, null);
-
- return createRelation;
-
- }
-
- /**
- * add property value node with default value of override value and associate it to the capability instance node
- *
- * @param properties
- * - properties definition. old also default value
- * @param capabilityInstance
- * - hold also properties new value(if exists)
- * @param capabilityInstData
- * - the graph node which we associate the properties value node to.
- * @return
- */
- private Either<List<GraphRelation>, TitanOperationStatus> addPropertiesToCapabilityInstance(Map<String, PropertyDefinition> properties, CapabiltyInstance capabilityInstance, CapabilityInstData capabilityInstData) {
-
- List<GraphRelation> relationsResult = new ArrayList<GraphRelation>();
-
- if (properties != null) {
- for (Entry<String, PropertyDefinition> entry : properties.entrySet()) {
-
- String paramName = entry.getKey();
-
- PropertyDefinition propertyDefinition = entry.getValue();
-
- String propertyValue = setPropertyValue(capabilityInstance, paramName, propertyDefinition);
-
- PropertyValueData propertyValueData = buildPropertyValueData(capabilityInstData.getUniqueId(), paramName, propertyValue);
-
- log.debug("Before creating property value data node {} in graph.", propertyValueData);
- Either<PropertyValueData, TitanOperationStatus> createNode = titanGenericDao.createNode(propertyValueData, PropertyValueData.class);
- log.debug("Before creating property value data node {} in graph. status is {}", propertyValueData, createNode);
- if (createNode.isRight()) {
- TitanOperationStatus status = createNode.right().value();
- log.error("Failed to create property value node in graph {}. status is {}", propertyValueData, status);
- return Either.right(status);
- }
-
- PropertyValueData propertyValueDataCreated = createNode.left().value();
-
- Either<GraphRelation, TitanOperationStatus> createRelation = associateCapabilityInstToPropertyValue(capabilityInstData, paramName, propertyValueDataCreated);
-
- if (createRelation.isRight()) {
- TitanOperationStatus status = createNode.right().value();
- log.error("Failed to create relation between capability instance {} to property value {} in graph. status is {}", capabilityInstData.getUniqueId(), propertyValueDataCreated.getUniqueId(), status);
- return Either.right(status);
- }
-
- relationsResult.add(createRelation.left().value());
-
- }
- }
-
- return Either.left(relationsResult);
- }
-
- private Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToPropertyValue(CapabilityInstData capabilityInstData, String paramName, PropertyValueData propertyValueDataCreated) {
-
- Map<String, Object> edgeProps = new HashMap<String, Object>();
- edgeProps.put(GraphPropertiesDictionary.NAME.getProperty(), paramName);
- log.debug("Begin creating relation between capability instance {} to property value {} in graph.", capabilityInstData, propertyValueDataCreated);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(capabilityInstData, propertyValueDataCreated, GraphEdgeLabels.PROPERTY_VALUE, edgeProps);
- log.debug("After creating relation between capability instance {} to property value {} in graph. status is {}", capabilityInstData, propertyValueDataCreated, createRelation);
-
- return createRelation;
- }
-
- private String setPropertyValue(CapabiltyInstance capabilityInstance, String paramName, PropertyDefinition propertyDefinition) {
- String propertyValue = NA;
- if (propertyDefinition.getDefaultValue() != null) {
- propertyValue = propertyDefinition.getDefaultValue();
- }
- Map<String, String> propertiesValue = null;
- if (capabilityInstance != null) {
- propertiesValue = capabilityInstance.getProperties();
- if (propertiesValue != null) {
- String tmpValue = propertiesValue.get(paramName);
- if (tmpValue != null) {
- propertyValue = tmpValue;
- }
- }
- }
- return propertyValue;
- }
-
- private String buildPropertykeyValue(String paramName, String paramValue) {
- return paramName + EQUAL_SIGN + paramValue;
- }
-
- private PropertyValueData buildPropertyValueData(String capabilityInstDataUid, String paramName, String propertyValue) {
- PropertyValueData propertyValueData = new PropertyValueData();
- propertyValueData.setValue(propertyValue);
- String uid = UniqueIdBuilder.buildPropertyValueUniqueId(capabilityInstDataUid, paramName);
- propertyValueData.setUniqueId(uid);
- Long creationDate = System.currentTimeMillis();
- propertyValueData.setCreationTime(creationDate);
- propertyValueData.setModificationTime(creationDate);
- return propertyValueData;
- }
-
- private Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceNode(String capabilityName, RequirementImplData reqImplData) {
-
- CapabilityInstData capabilityInstData = new CapabilityInstData();
- String uniqueId = UniqueIdBuilder.buildCapabilityInstanceUid(reqImplData.getUniqueId(), capabilityName);
-
- capabilityInstData.setUniqueId(uniqueId);
- // capabilityInstData.setProperties(instanceProperties);
- Long creationDate = System.currentTimeMillis();
- capabilityInstData.setCreationTime(creationDate);
- capabilityInstData.setModificationTime(creationDate);
-
- log.debug("Before creating capability instance node in graph {}", capabilityInstData);
- Either<CapabilityInstData, TitanOperationStatus> createNode = titanGenericDao.createNode(capabilityInstData, CapabilityInstData.class);
- log.debug("After creating capability instance node in graph {}. status is {}", capabilityInstData, createNode);
-
- return createNode;
- }
-
- private void checkNodeIdImplementsRequirementNode(String nodeIdImpl, String reqNode) {
- // TODO Auto-generated method stub
-
- }
-
- private void checkImplNodeContainsReqCapability(String reqCapability, List<ImmutablePair<CapabilityData, GraphEdge>> capabilitiesValue) {
- // TODO Auto-generated method stub
-
- }
-
- public Either<Map<String, List<RequirementDefinition>>, StorageOperationStatus> getAllRequirementsOfResourceOnly(String resourceId, boolean inTransaction) {
-
- Either<Map<String, List<RequirementDefinition>>, StorageOperationStatus> result = null;
-
- try {
-
- Map<String, RequirementDefinition> requirements = new HashMap<String, RequirementDefinition>();
- Set<String> caseInsensitiveReqNames = new HashSet<>();
- TitanOperationStatus status = findAllRequirementsNonRecursive(resourceId, requirements, caseInsensitiveReqNames);
-
- if (status != TitanOperationStatus.OK) {
- log.error("Failed to get all requirements of resource {}. status is {}", resourceId, status);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- } else {
- // TODO handle requirementImpl
- result = Either.left(convertRequirementMap(requirements, null, null));
- }
- return result;
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- @Override
- public Either<Map<String, RequirementDefinition>, TitanOperationStatus> getResourceRequirements(String resourceId) {
-
- Either<Map<String, RequirementDefinition>, TitanOperationStatus> result = null;
-
- Map<String, RequirementDefinition> requirements = new HashMap<String, RequirementDefinition>();
- Set<String> caseInsensitiveReqNames = new HashSet<>();
-
- TitanOperationStatus status = findAllRequirementsRecursively(resourceId, requirements, caseInsensitiveReqNames);
- if (status != TitanOperationStatus.OK) {
- log.error("Failed to get all requirements of resource {}. status is {}", resourceId, status);
- return Either.right(status);
- } else {
- log.debug("The requirements returned for resource {} are {}", resourceId, requirements);
-
- if (requirements != null) {
- for (Entry<String, RequirementDefinition> entry : requirements.entrySet()) {
- String reqName = entry.getKey();
- Either<RequirementImplDef, TitanOperationStatus> reqImplRes = this.getRequirementImplOfResource(reqName, resourceId);
- if (reqImplRes.isRight()) {
-
- TitanOperationStatus reqImplResStatus = reqImplRes.right().value();
- if (reqImplResStatus == TitanOperationStatus.NOT_FOUND) {
- log.debug("Cannot find implementation of requirement {} under resource {}", reqName, resourceId);
- } else {
- log.error("Cannot find implementation of requirement {} under resource {}", reqName, resourceId);
- return Either.right(reqImplResStatus);
- }
- } else {
- RequirementDefinition requirementDefinition = entry.getValue();
- // RequirementImplDef requirementImplDef =
- // reqImplRes.left().value();
- // requirementDefinition.setRequirementImpl(requirementImplDef);
- }
- }
- }
- log.debug("The requirements returned for resource {} after fetching requirement impl are {}", resourceId, requirements);
-
- result = Either.left(requirements);
-
- return result;
- }
-
- }
-
- @Override
- public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements(String resourceId, boolean inTransaction) {
-
- Either<Map<String, RequirementDefinition>, StorageOperationStatus> result = null;
-
- try {
-
- Either<Map<String, RequirementDefinition>, TitanOperationStatus> internalResult = getResourceRequirements(resourceId);
- if (internalResult.isRight()) {
- TitanOperationStatus status = internalResult.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to fetch requirements of resource {} . status is {}", resourceId, status);
- }
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- Map<String, RequirementDefinition> value = internalResult.left().value();
-
- result = Either.left(value);
- return result;
- } finally {
- if (!inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements(String resourceId) {
-
- return getAllResourceRequirements(resourceId, false);
-
- }
-
- public TitanOperationStatus findAllRequirementsRecursively(String resourceId, Map<String, RequirementDefinition> requirements, Set<String> caseInsensitiveReqNames) {
-
- TitanOperationStatus nonRecursiveResult = findAllRequirementsNonRecursive(resourceId, requirements, caseInsensitiveReqNames);
- if (!nonRecursiveResult.equals(TitanOperationStatus.OK) && !nonRecursiveResult.equals(TitanOperationStatus.NOT_FOUND)) {
- return nonRecursiveResult;
- }
-
- Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
- ResourceMetadataData.class);
-
- if (parentNodes.isRight()) {
- TitanOperationStatus parentNodesStatus = parentNodes.right().value();
- if (parentNodesStatus == TitanOperationStatus.NOT_FOUND) {
- log.debug("Finish to lookup for parnet requirements");
- return TitanOperationStatus.OK;
- } else {
- log.error("Failed to find parent requirements of resource {} . status is {}", resourceId, parentNodesStatus);
- return parentNodesStatus;
- }
- }
- ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value();
- String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId();
- TitanOperationStatus addParentReqStatus = findAllRequirementsRecursively(parentUniqueId, requirements, caseInsensitiveReqNames);
-
- if (addParentReqStatus != TitanOperationStatus.OK) {
- log.error("Failed to fetch all requirements of resource {}", parentUniqueId);
- return addParentReqStatus;
- }
-
- return TitanOperationStatus.OK;
- }
-
- private TitanOperationStatus findAllRequirementsNonRecursive(String resourceId, Map<String, RequirementDefinition> requirements, Set<String> caseInsensitiveReqNames) {
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> requirementNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.REQUIREMENT,
- NodeTypeEnum.Requirement, RequirementData.class);
-
- if (requirementNodes.isRight()) {
- TitanOperationStatus status = requirementNodes.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- return status;
- }
- } else {
- List<ImmutablePair<RequirementData, GraphEdge>> requirementList = requirementNodes.left().value();
- if (requirementList != null) {
- for (ImmutablePair<RequirementData, GraphEdge> requirementPair : requirementList) {
- String reqUniqueId = requirementPair.getKey().getUniqueId();
- Map<String, Object> edgeProps = requirementPair.getValue().getProperties();
- String reqName = null;
- if (edgeProps != null) {
- reqName = (String) edgeProps.get(GraphPropertiesDictionary.NAME.getProperty());
- if (reqName == null) {
- log.error("The requirement name is missing on the edge of requirement {}", reqUniqueId);
- return TitanOperationStatus.INVALID_ELEMENT;
- }
- } else {
- log.error("The requirement name is missing on the edge of requirement {}", reqUniqueId);
- return TitanOperationStatus.INVALID_ELEMENT;
- }
- Either<RequirementDefinition, TitanOperationStatus> requirementDefRes = this.getRequirement(reqUniqueId);
- if (requirementDefRes.isRight()) {
- TitanOperationStatus status = requirementDefRes.right().value();
- log.error("Failed to get requirement properties of requirement {}", reqUniqueId);
- return status;
- }
-
- RequirementDefinition requirementDefinition = requirementDefRes.left().value();
- requirementDefinition.setName(reqName);
- // US631462
- if (caseInsensitiveReqNames.contains(reqName.toLowerCase())) {
- log.debug("The requirement {} was already defined in derived resource (case insensitive). Ignore {} from resource {}", reqName, reqName, resourceId);
- } else {
- requirements.put(reqName, requirementDefinition);
- caseInsensitiveReqNames.add(reqName.toLowerCase());
- }
-
- }
- }
- }
- return TitanOperationStatus.OK;
- }
-
- public StorageOperationStatus deleteRequirementFromGraph(String requirementId) {
- log.debug("Before deleting requirement from graph {}", requirementId);
- Either<RequirementData, TitanOperationStatus> deleteNodeStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementId, RequirementData.class);
- if (deleteNodeStatus.isRight()) {
- log.error("failed to delete requirement with id {}. status={}", requirementId, deleteNodeStatus.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNodeStatus.right().value());
- }
- return StorageOperationStatus.OK;
- }
-
- public Either<Map<String, RequirementDefinition>, StorageOperationStatus> deleteAllRequirements(String resourceId) {
-
- return getAllResourceRequirements(resourceId, false);
-
- }
-
- public Either<Map<String, RequirementDefinition>, StorageOperationStatus> deleteAllRequirements(String resourceId, boolean inTransaction) {
-
- Either<Map<String, RequirementDefinition>, StorageOperationStatus> result = null;
-
- try {
- Either<Map<String, RequirementDefinition>, TitanOperationStatus> deleteAllRes = deleteAllRequirementsOfResource(resourceId);
- if (deleteAllRes.isRight()) {
- TitanOperationStatus status = deleteAllRes.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to delete requirements of resource {}. status is {}", resourceId, status);
- }
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- Map<String, RequirementDefinition> value = deleteAllRes.left().value();
- result = Either.left(value);
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- public Either<Map<String, RequirementDefinition>, TitanOperationStatus> deleteAllRequirementsOfResource(String resourceId) {
-
- Map<String, RequirementDefinition> requirements = new HashMap<String, RequirementDefinition>();
- Set<String> caseInsensitiveReqNames = new HashSet<>();
- TitanOperationStatus requirementsRes = findAllRequirementsNonRecursive(resourceId, requirements, caseInsensitiveReqNames);
- if (requirementsRes != TitanOperationStatus.OK) {
- return Either.right(requirementsRes);
- }
-
- if (requirements.isEmpty()) {
- return Either.right(TitanOperationStatus.NOT_FOUND);
- }
-
- for (Entry<String, RequirementDefinition> entry : requirements.entrySet()) {
- RequirementDefinition requirementDefinition = entry.getValue();
-
- String requirementUid = requirementDefinition.getUniqueId();
-
- Either<RequirementData, TitanOperationStatus> deleteNodeRes = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementUid, RequirementData.class);
- if (deleteNodeRes.isRight()) {
- TitanOperationStatus status = deleteNodeRes.right().value();
- log.error("Failed to delete requirement {} of resource ", requirementUid, resourceId);
- return Either.right(status);
- }
- }
-
- return Either.left(requirements);
-
- }
-
- public Map<String, List<RequirementDefinition>> convertRequirementMap(Map<String, RequirementDefinition> requirementMap, String ownerId, String ownerName) {
-
- Map<String, List<RequirementDefinition>> typeToRequirementMap = new HashMap<String, List<RequirementDefinition>>();
- requirementMap.forEach((reqName, requirement) -> {
- // requirement.setOwnerId(ownerId);
- // requirement.setOwnerName(ownerName);
- if (typeToRequirementMap.containsKey(requirement.getCapability())) {
- typeToRequirementMap.get(requirement.getCapability()).add(requirement);
- } else {
- List<RequirementDefinition> list = new ArrayList<RequirementDefinition>();
- list.add(requirement);
- typeToRequirementMap.put(requirement.getCapability(), list);
- }
- });
- return typeToRequirementMap;
- }
-
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java
deleted file mode 100644
index 2cc78eade2..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java
+++ /dev/null
@@ -1,3040 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanVertex;
-import fj.data.Either;
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.openecomp.sdc.be.config.BeEcompErrorManager;
-import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
-import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.*;
-import org.openecomp.sdc.be.model.cache.ComponentCache;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
-import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation;
-import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
-import org.openecomp.sdc.be.model.operations.api.IAttributeOperation;
-import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.migration.MigrationMalformedDataLogger;
-import org.openecomp.sdc.be.model.operations.utils.GraphDeleteUtil;
-import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
-import org.openecomp.sdc.be.resources.data.PropertyData;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.openecomp.sdc.be.resources.data.TagData;
-import org.openecomp.sdc.be.resources.data.UniqueIdData;
-import org.openecomp.sdc.be.resources.data.UserData;
-import org.openecomp.sdc.be.resources.data.category.CategoryData;
-import org.openecomp.sdc.be.resources.data.category.SubCategoryData;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
-import org.openecomp.sdc.common.datastructure.Wrapper;
-import org.openecomp.sdc.common.util.PairUtils;
-import org.openecomp.sdc.common.util.ValidationUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.slf4j.MDC;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.UUID;
-import java.util.function.Predicate;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-@org.springframework.stereotype.Component("resource-operation")
-@Deprecated
-public class ResourceOperation extends ComponentOperation implements IResourceOperation {
-
- public ResourceOperation() {
- super();
- }
-
- private static Logger log = LoggerFactory.getLogger(ResourceOperation.class.getName());
-
- @javax.annotation.Resource
- private PropertyOperation propertyOperation;
-
- @javax.annotation.Resource
- private IAttributeOperation attributeOperation;
-
- @javax.annotation.Resource
- private RequirementOperation requirementOperation;
-
- @javax.annotation.Resource
- private CapabilityOperation capabilityOperation;
-
- @javax.annotation.Resource
- private InterfaceLifecycleOperation interfaceLifecycleOperation;
-
- @javax.annotation.Resource
- private IElementOperation elementOperation;
-
- @javax.annotation.Resource
- private IAdditionalInformationOperation addioAdditionalInformationOperation;
-
- @javax.annotation.Resource
- private GroupOperation groupOperation;
-
- @javax.annotation.Resource
- private ComponentCache componentCache;
-
- private Gson prettyJson = new GsonBuilder().setPrettyPrinting().create();
-
- private GraphDeleteUtil graphDeleteUtil = new GraphDeleteUtil();
-
- public static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1");
- public static Pattern uuidNormativeNewVersion = Pattern.compile("^\\d{1,}.0");
-
- @Override
- public Either<Resource, StorageOperationStatus> createResource(Resource resource) {
- return createResource(resource, false);
- }
-
- @Override
- public Either<Resource, StorageOperationStatus> createResource(Resource resource, boolean inTransaction) {
-
- Either<Resource, StorageOperationStatus> result = null;
-
- try {
- generateUUID(resource);
-
- ResourceMetadataData resourceData = getResourceMetaDataFromResource(resource);
- String resourceUniqueId = resource.getUniqueId();
- if (resourceUniqueId == null) {
- resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId();
- resourceData.getMetadataDataDefinition().setUniqueId(resourceUniqueId);
- }
- resourceData.getMetadataDataDefinition().setHighestVersion(true);
-
- String userId = resource.getCreatorUserId();
-
- Either<TitanVertex, TitanOperationStatus> findUser = findUserVertex(userId);
-
- if (findUser.isRight()) {
- TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user {} in the graph. status is {}", userId, status);
- return sendError(status, StorageOperationStatus.USER_NOT_FOUND);
- }
-
- TitanVertex creatorVertex = findUser.left().value();
- TitanVertex updaterVertex = creatorVertex;
- String updaterUserId = resource.getLastUpdaterUserId();
- if (updaterUserId != null && !updaterUserId.equals(userId)) {
- findUser = findUserVertex(updaterUserId);
- if (findUser.isRight()) {
- TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user {} in the graph. status is {}", userId, status);
- return sendError(status, StorageOperationStatus.USER_NOT_FOUND);
- } else {
- updaterVertex = findUser.left().value();
- }
- }
-
- // get derived from resources
- List<ResourceMetadataData> derivedResources = null;
- Either<List<ResourceMetadataData>, StorageOperationStatus> derivedResourcesResult = findDerivedResources(resource);
- if (derivedResourcesResult.isRight()) {
- result = Either.right(derivedResourcesResult.right().value());
- return result;
- } else {
- derivedResources = derivedResourcesResult.left().value();
- }
-
- List<String> tags = resource.getTags();
- if (tags != null && false == tags.isEmpty()) {
- Either<List<TagData>, StorageOperationStatus> tagsResult = createNewTagsList(tags);
- if (tagsResult.isRight()) {
- result = Either.right(tagsResult.right().value());
- return result;
- }
- List<TagData> tagsToCreate = tagsResult.left().value();
- StorageOperationStatus status = createTagNodesOnGraph(tagsToCreate);
- if (!status.equals(StorageOperationStatus.OK)) {
- result = Either.right(status);
- return result;
- }
- }
-
- Either<TitanVertex, TitanOperationStatus> createdVertex = titanGenericDao.createNode(resourceData);
- if (createdVertex.isRight()) {
- TitanOperationStatus status = createdVertex.right().value();
- log.error("Error returned after creating resource data node {}. status returned is ", resourceData, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- TitanVertex metadataVertex = createdVertex.left().value();
-
- TitanOperationStatus associateMetadata = associateMetadataToResource(resourceData, creatorVertex, updaterVertex, derivedResources, metadataVertex);
- if (associateMetadata != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateMetadata));
- return result;
- }
- StorageOperationStatus associateCategory = assosiateMetadataToCategory(resource, resourceData);
- if (associateCategory != StorageOperationStatus.OK) {
- result = Either.right(associateCategory);
- return result;
- }
-
- TitanOperationStatus associateProperties = associatePropertiesToResource(metadataVertex, resourceUniqueId, resource.getProperties(), derivedResources);
- if (associateProperties != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateProperties));
- return result;
- }
-
- TitanOperationStatus associateAttributes = associateAttributesToResource(metadataVertex, resource.getAttributes(), resourceUniqueId);
- if (associateAttributes != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateAttributes));
- return result;
- }
-
- TitanOperationStatus associateInputs = associateInputsToComponent(metadataVertex, resourceUniqueId, resource.getInputs());
- if (associateInputs != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateInputs));
- return result;
- }
-
- StorageOperationStatus associateRequirements = associateRequirementsToResource(metadataVertex, resourceUniqueId, resource.getRequirements());
- if (associateRequirements != StorageOperationStatus.OK) {
- result = Either.right(associateRequirements);
- return result;
- }
-
- StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(metadataVertex, resourceUniqueId, resource.getCapabilities());
- if (associateCapabilities != StorageOperationStatus.OK) {
- result = Either.right(associateCapabilities);
- return result;
- }
-
- StorageOperationStatus associateInterfaces = associateInterfacesToResource(resourceData, resource.getInterfaces(), metadataVertex);
- if (associateInterfaces != StorageOperationStatus.OK) {
- result = Either.right(associateInterfaces);
- return result;
- }
-
- Map<String, ArtifactDefinition> resourceArtifacts = resource.getArtifacts();
- Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts();
- Map<String, ArtifactDefinition> toscaArtifacts = resource.getToscaArtifacts();
- if (resourceArtifacts != null) {
- if (deploymentArtifacts != null) {
- resourceArtifacts.putAll(deploymentArtifacts);
- }
- } else {
- resourceArtifacts = deploymentArtifacts;
- }
- if (toscaArtifacts != null) {
- if (resourceArtifacts != null) {
- resourceArtifacts.putAll(toscaArtifacts);
- } else {
- resourceArtifacts = toscaArtifacts;
- }
- }
-
- StorageOperationStatus associateArtifacts = associateArtifactsToResource(metadataVertex, resourceUniqueId, resourceArtifacts);
- if (associateArtifacts != StorageOperationStatus.OK) {
- result = Either.right(associateArtifacts);
- return result;
- }
-
- List<AdditionalInformationDefinition> additionalInformation = resource.getAdditionalInformation();
- StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(metadataVertex, resourceUniqueId, additionalInformation);
- if (addAdditionalInformation != StorageOperationStatus.OK) {
- result = Either.right(addAdditionalInformation);
- return result;
- }
-
- result = this.getResource(resourceUniqueId, true);
- if (result.isRight()) {
- log.error("Cannot get full resource from the graph. status is {}", result.right().value());
- return Either.right(result.right().value());
- }
-
- if (log.isDebugEnabled()) {
- String json = prettyJson.toJson(result.left().value());
- log.debug("Resource retrieved is {}", json);
- }
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- private StorageOperationStatus assosiateMetadataToCategory(Resource resource, ResourceMetadataData resourceData) {
- // get category
- String categoryName = resource.getCategories().get(0).getName();
- String subcategoryName = resource.getCategories().get(0).getSubcategories().get(0).getName();
-
- CategoryData categoryData = null;
- Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class);
- if (categoryResult.isRight()) {
- StorageOperationStatus status = categoryResult.right().value();
- log.error("Cannot find category {} in the graph. status is {}", categoryName, status);
- return categoryResult.right().value();
- }
- categoryData = categoryResult.left().value();
- if (categoryData != null) {
- Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(),
- GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class);
- if (childrenNodes.isRight()) {
- log.debug("Faield to fetch sub categories for resource category {}", categoryData.getCategoryDataDefinition().getName());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(childrenNodes.right().value());
- }
- for (ImmutablePair<SubCategoryData, GraphEdge> pair : childrenNodes.left().value()) {
- SubCategoryData subcategoryData = pair.left;
- if (subcategoryData.getSubCategoryDataDefinition().getName().equals(subcategoryName)) {
- Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.createRelation(resourceData, subcategoryData, GraphEdgeLabels.CATEGORY, null);
- log.debug("After associating resource {} to subcategory {}. Edge type is {}", resourceData.getUniqueId(), subcategoryData, GraphEdgeLabels.CATEGORY);
- if (result.isRight()) {
- log.error("Faield to associate resource {} to category {}. Edge type is {}", resourceData.getUniqueId(), categoryData, GraphEdgeLabels.CATEGORY);
- return DaoStatusConverter.convertTitanStatusToStorageStatus(result.right().value());
- }
-
- }
- }
- }
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus addAdditionalInformationToResource(TitanVertex metadataVertex, String resourceUniqueId, List<AdditionalInformationDefinition> additionalInformation) {
-
- StorageOperationStatus result = null;
- if (additionalInformation == null || true == additionalInformation.isEmpty()) {
- result = super.addAdditionalInformation(NodeTypeEnum.Resource, resourceUniqueId, null, metadataVertex);
- } else {
- if (additionalInformation.size() == 1) {
- result = super.addAdditionalInformation(NodeTypeEnum.Resource, resourceUniqueId, additionalInformation.get(0));
- } else {
- result = StorageOperationStatus.BAD_REQUEST;
- log.info("Cannot create resource with more than one additional information object. The number of received object is {}", additionalInformation.size());
- }
- }
- return result;
- }
-
- private void generateUUID(Resource resource) {
- String prevUUID = resource.getUUID();
- String version = resource.getVersion();
- if ((prevUUID == null && uuidNormativeNewVersion.matcher(version).matches()) || uuidNewVersion.matcher(version).matches()) {
- UUID uuid = UUID.randomUUID();
- resource.setUUID(uuid.toString());
- MDC.put("serviceInstanceID", uuid.toString());
- }
- }
-
- @Override
- public Either<Resource, StorageOperationStatus> overrideResource(Resource resource, Resource resourceSaved, boolean inTransaction) {
- Either<Resource, StorageOperationStatus> result = null;
- try {
- String resourceId = resourceSaved.getUniqueId();
-
- // override interfaces to copy only resource's interfaces and not
- // derived interfaces
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> interfacesOfResourceOnly = interfaceLifecycleOperation.getAllInterfacesOfResource(resourceSaved.getUniqueId(), false, true);
- if (interfacesOfResourceOnly.isRight()) {
- log.error("failed to get interfaces of resource. resourceId {} status is {}", resourceId, interfacesOfResourceOnly.right().value());
- result = Either.right(interfacesOfResourceOnly.right().value());
- return result;
- }
- resource.setInterfaces(interfacesOfResourceOnly.left().value());
- resource.setArtifacts(resourceSaved.getArtifacts());
- resource.setDeploymentArtifacts(resourceSaved.getDeploymentArtifacts());
- resource.setGroups(resourceSaved.getGroups());
- resource.setInputs(null);
- resource.setLastUpdateDate(null);
- resource.setHighestVersion(true);
-
- // delete former resource
- Either<Resource, StorageOperationStatus> deleteResource = deleteResource(resourceId, true);
- if (deleteResource.isRight()) {
- log.error("failed to delete old resource with id {}. status = {}", resourceId, deleteResource.right().value());
- result = deleteResource;
- return result;
- }
-
- Either<Resource, StorageOperationStatus> createResource = createResource(resource, true);
- if (createResource.isRight()) {
- log.error("failed to create new version of resource {} status = {}", resourceId, createResource.right().value());
- result = createResource;
- return result;
- }
- Resource newResource = createResource.left().value();
-
- Either<List<GroupDefinition>, StorageOperationStatus> cloneGroupEither = cloneGroups(resource, newResource, null, inTransaction);
- if (cloneGroupEither.isLeft()) {
- newResource.setGroups(cloneGroupEither.left().value());
- } else if (cloneGroupEither.right().value() != StorageOperationStatus.OK) {
- log.error("failed to clone group of resource {} status = {}", resourceId, cloneGroupEither.right().value());
- result = Either.right(cloneGroupEither.right().value());
- return result;
- }
-
- result = Either.left(newResource);
- return result;
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- private StorageOperationStatus associateCapabilitiesToResource(TitanVertex metadataVertex, String resourceIda, Map<String, List<CapabilityDefinition>> capabilities) {
- StorageOperationStatus addCapabilityToResource = null;
- if (capabilities != null) {
- for (Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
-
- List<CapabilityDefinition> capDefinition = entry.getValue();
- for (CapabilityDefinition item : capDefinition) {
- addCapabilityToResource = capabilityOperation.addCapability(metadataVertex, resourceIda, item.getName(), item, true);
- if (!addCapabilityToResource.equals(StorageOperationStatus.OK)) {
- return addCapabilityToResource;
- }
-
- }
- }
-
- }
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus associateRequirementsToResource(TitanVertex metadataVertex, String resourceId, Map<String, List<RequirementDefinition>> requirements) {
-
- if (requirements != null) {
- for (Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
-
- List<RequirementDefinition> reqDefinition = entry.getValue();
- for (RequirementDefinition item : reqDefinition) {
- StorageOperationStatus addRequirementToResource = requirementOperation.addRequirementToResource(metadataVertex, item.getName(), item, resourceId, true);
-
- if (!addRequirementToResource.equals(StorageOperationStatus.OK)) {
- return addRequirementToResource;
- }
- }
- }
- }
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus associateArtifactsToResource(TitanVertex metadataVertex, String resourceId, Map<String, ArtifactDefinition> artifacts) {
-
- StorageOperationStatus status = StorageOperationStatus.OK;
- if (artifacts != null) {
- Map<ArtifactDefinition, ArtifactDefinition> heatEnvMap = new HashMap<ArtifactDefinition, ArtifactDefinition>();
- for (Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
-
- ArtifactDefinition artifactDefinition = entry.getValue();
-
- ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactDefinition.getArtifactType());
- if(artifactType != ArtifactTypeEnum.HEAT_ENV){
- status = artifactOperation.addArifactToComponent(artifactDefinition, resourceId, NodeTypeEnum.Resource, false, metadataVertex);
- }else{
- Optional<ArtifactDefinition> op = artifacts.values().stream().filter(p -> p.getUniqueId().equals(artifactDefinition.getGeneratedFromId())).findAny();
- if(op.isPresent()){
- heatEnvMap.put(artifactDefinition, op.get());
- }
-
-
- }
-
- if (!status.equals(StorageOperationStatus.OK)) {
- return status;
- }
- }
- for(Entry<ArtifactDefinition, ArtifactDefinition> entry : heatEnvMap.entrySet()){
- Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = artifactOperation.addHeatEnvArtifact(entry.getKey(), entry.getValue(), resourceId, NodeTypeEnum.Resource, false);
- if (addHeatEnvArtifact.isRight()) {
- log.debug("failed to create heat env artifact on resource instance");
- return addHeatEnvArtifact.right().value();
- }
- }
- }
- return status;
-
- }
-
- private StorageOperationStatus associateInterfacesToResource(ResourceMetadataData resourceData, Map<String, InterfaceDefinition> interfaces, TitanVertex metadataVertex) {
-
- if (interfaces != null) {
- for (Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
-
- InterfaceDefinition interfaceDefinition = entry.getValue();
- StorageOperationStatus status;
- if (((ResourceMetadataDataDefinition) resourceData.getMetadataDataDefinition()).isAbstract()) {
- status = interfaceLifecycleOperation.associateInterfaceToNode(resourceData, interfaceDefinition, metadataVertex);
- } else {
- status = interfaceLifecycleOperation.createInterfaceOnResource(interfaceDefinition, resourceData.getMetadataDataDefinition().getUniqueId(), interfaceDefinition.getType(), false, true, metadataVertex);
- }
-
- if (!status.equals(StorageOperationStatus.OK)) {
- return status;
- }
- }
- }
- return StorageOperationStatus.OK;
-
- }
-
- private Either<Resource, StorageOperationStatus> sendError(TitanOperationStatus status, StorageOperationStatus statusIfNotFound) {
- Either<Resource, StorageOperationStatus> result;
- if (status == TitanOperationStatus.NOT_FOUND) {
- result = Either.right(statusIfNotFound);
- return result;
- } else {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- }
-
- private TitanOperationStatus associatePropertiesToResource(TitanVertex metadatVertex, String resourceId, List<PropertyDefinition> properties, List<ResourceMetadataData> derivedResources) {
-
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- log.debug("Cannot find any data type. Status is {}.", status);
- return status;
- }
-
- Map<String, PropertyDefinition> convertedProperties = new HashMap<>();
-
- if (properties != null) {
- for (PropertyDefinition propertyDefinition : properties) {
- convertedProperties.put(propertyDefinition.getName(), propertyDefinition);
- }
-
- Either<Map<String, PropertyDefinition>, TitanOperationStatus> getPropertiesOfAllDerivedFromRes = getPropertiesOfAllDerivedFrom(derivedResources);
-
- if(getPropertiesOfAllDerivedFromRes.isRight()){
- TitanOperationStatus status = getPropertiesOfAllDerivedFromRes.right().value();
- log.debug("Cannot fetch properties of all derived from resources. Status is {}.", status);
- return status;
- }
-
- Map<String, PropertyDefinition> allDerivedFromProperties = getPropertiesOfAllDerivedFromRes.left().value();
-
- TitanOperationStatus validatePropertyNamesUniqunessStatus = validatePropertyNamesUniquness(properties, allDerivedFromProperties);
-
- if(validatePropertyNamesUniqunessStatus != TitanOperationStatus.OK){
- return validatePropertyNamesUniqunessStatus;
- }
-
- return propertyOperation.addPropertiesToGraph(metadatVertex, convertedProperties, allDataTypes.left().value(), resourceId);
- }
-
- return TitanOperationStatus.OK;
-
- }
-
- private TitanOperationStatus validatePropertyNamesUniquness(List<PropertyDefinition> properties, Map<String, PropertyDefinition> allDerivedFromProperties) {
-
- TitanOperationStatus result = TitanOperationStatus.OK;
- Optional<PropertyDefinition> propertyOptional= properties.stream()
- //filters out properties with the same name and different type
- .filter(prop -> allDerivedFromProperties.containsKey(prop.getName()) && !prop.getType().equals(allDerivedFromProperties.get(prop.getName()).getType()))
- //Searches for any matching value
- .findAny();
- if(propertyOptional.isPresent()){
- log.error("Property with name {} and type {} already exists in derived from resource. ", propertyOptional.get().getName(), allDerivedFromProperties.get( propertyOptional.get().getName()).getType());
- result = TitanOperationStatus.ALREADY_EXIST;
- }
- return result;
- }
-
- private Either<Map<String, PropertyDefinition>, TitanOperationStatus> getPropertiesOfAllDerivedFrom(List<ResourceMetadataData> derivedResources) {
- Map<String, PropertyDefinition> allDerivedProperties = new HashMap<>();
- Either<Map<String, PropertyDefinition>, TitanOperationStatus> getPropertiesOfAllDerivedFromRes = Either.left(allDerivedProperties);
- String currResourceName = null ;
- if(!CollectionUtils.isEmpty(derivedResources)){
- try{
- for(int i = derivedResources.size() - 1; i >= 0 ; --i){
- ResourceMetadataData currDerivedResource = derivedResources.get(i);
- currResourceName = currDerivedResource.getMetadataDataDefinition().getName();
- Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> res =
- titanGenericDao.getChildrenNodes( currDerivedResource.getUniqueIdKey(), (String)currDerivedResource.getUniqueId(), GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property, PropertyData.class);
- if(res.isRight() && res.right().value() != TitanOperationStatus.NOT_FOUND){
- getPropertiesOfAllDerivedFromRes = Either.right(res.right().value());
- break;
- }else if(res.isLeft()){
- allDerivedProperties.putAll(res.left().value().stream()
- //Maps PropertyData converted to PropertyDefinition
- .map(pair-> propertyOperation.convertPropertyDataToPropertyDefinition(pair.getLeft(), (String)pair.getRight().getProperties().get(GraphPropertiesDictionary.NAME.getProperty()), (String)currDerivedResource.getUniqueId()))
- //and collects it to a map
- .collect(Collectors.toMap(entry->entry.getName(), entry->entry)));
- }
- }
- }
- catch(Exception e){
- log.error("Exception occured during fetch properties of resource {}. ", currResourceName);
- }
- }
- return getPropertiesOfAllDerivedFromRes;
- }
-
- private TitanOperationStatus associateAttributesToResource(TitanVertex metadataVertex, List<PropertyDefinition> attributes, String resourceId) {
- TitanOperationStatus operationStatus = TitanOperationStatus.OK;
-
- Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll();
- if (allDataTypes.isRight()) {
- TitanOperationStatus status = allDataTypes.right().value();
- log.debug("Cannot find any data type. Status is {}.", status);
- return status;
- }
-
- if (attributes != null) {
- Map<String, PropertyDefinition> convertedAttributes = attributes.stream().collect(Collectors.toMap(e -> e.getName(), e -> e));
- operationStatus = attributeOperation.addAttributesToGraph(metadataVertex, convertedAttributes, resourceId, allDataTypes.left().value());
- }
- return operationStatus;
- }
-
- private TitanOperationStatus associateMetadataToResource(ResourceMetadataData resourceData, TitanVertex creatorVertex, TitanVertex updaterVertex, List<ResourceMetadataData> derivedResources, TitanVertex metadataVertex) {
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.STATE.getProperty(), resourceData.getMetadataDataDefinition().getState());
-
- TitanOperationStatus result = titanGenericDao.createEdge(updaterVertex, metadataVertex, GraphEdgeLabels.STATE, props);
- log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, resourceData.getUniqueId(), GraphEdgeLabels.STATE);
- if (!result.equals(TitanOperationStatus.OK)) {
- return result;
- }
- result = titanGenericDao.createEdge(updaterVertex, metadataVertex, GraphEdgeLabels.LAST_MODIFIER, null);
- log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, resourceData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
- if (!result.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, resourceData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
- return result;
- }
-
- result = titanGenericDao.createEdge(creatorVertex, metadataVertex, GraphEdgeLabels.CREATOR, null);
- log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, resourceData.getUniqueId(), GraphEdgeLabels.CREATOR);
- if (!result.equals(TitanOperationStatus.OK)) {
- log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, resourceData.getUniqueId(), GraphEdgeLabels.CREATOR);
- return result;
- }
- // TODO Evg : need to change too..
- if (derivedResources != null) {
- for (ResourceMetadataData derivedResource : derivedResources) {
- log.debug("After associating resource {} to parent resource {}. Edge type is {}", resourceData.getUniqueId(), derivedResource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM);
- Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(resourceData, derivedResource, GraphEdgeLabels.DERIVED_FROM, null);
- if (createRelationResult.isRight()) {
- log.error("Failed to associate resource {} to derived ", resourceData.getUniqueId());
- return createRelationResult.right().value();
- }
- }
- }
-
- return TitanOperationStatus.OK;
- }
-
- public Either<List<ResourceMetadataData>, StorageOperationStatus> findDerivedResources(Resource resource) {
-
- List<ResourceMetadataData> derivedResources = new ArrayList<ResourceMetadataData>();
- List<String> derivedFromResources = resource.getDerivedFrom();
- if (derivedFromResources != null && false == derivedFromResources.isEmpty()) {
-
- for (String parentResource : derivedFromResources) {
-
- Map<String, Object> propertiesToMatch = new HashMap<String, Object>();
- propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
- // propertiesToMatch.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(),
- // true);
- propertiesToMatch.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), parentResource);
- propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> getParentResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class);
- List<ResourceMetadataData> resources = null;
- if (getParentResources.isRight()) {
- /*
- * log.debug( "Cannot find parent resource by tosca resource name {} in the graph. Try to find by name", parentResource);
- * Map<String, Object> propertiesWithResourceNameToMatch = new HashMap<String, Object>();
- * propertiesWithResourceNameToMatch.put( GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); propertiesWithResourceNameToMatch.put( GraphPropertiesDictionary.NAME.getProperty(), parentResource);
- * propertiesWithResourceNameToMatch.put( GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty( ), true);
- *
- * getParentResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesWithResourceNameToMatch, ResourceData.class); if (getParentResources.isRight()) { log.error(
- * "Cannot find parent resource by tosca resource name" + parentResource + " in the graph."); return Either.right(StorageOperationStatus. PARENT_RESOURCE_NOT_FOUND); }else{ resources = getParentResources.left().value();
- * hea
- * }
- */
- log.error("Cannot find parent resource by tosca resource name {} in the graph.", parentResource);
- return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND);
-
- } else {
- resources = getParentResources.left().value();
- if (resources == null || resources.size() == 0) {
- log.error("Cannot find parent resource by tosc name {} in the graph. resources size is empty", parentResource);
- return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND);
- } else {
- if (resources.size() > 1) {
- log.error("Multiple parent resources called {} found in the graph.", parentResource);
- return Either.right(StorageOperationStatus.MULTIPLE_PARENT_RESOURCE_FOUND);
- }
- ResourceMetadataData parentResourceData = resources.get(0);
- derivedResources.add(parentResourceData);
- }
-
- }
-
- }
- }
- return Either.left(derivedResources);
- }
-
- private ResourceMetadataData getResourceMetaDataFromResource(Resource resource) {
- ResourceMetadataData resourceData = new ResourceMetadataData((ResourceMetadataDataDefinition) resource.getComponentMetadataDefinition().getMetadataDataDefinition());
- if (resource.getNormalizedName() == null || resource.getNormalizedName().isEmpty()) {
- resourceData.getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(resource.getName()));
- }
- if (resource.getSystemName() == null || resource.getSystemName().isEmpty()) {
- resourceData.getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(resource.getName()));
- }
-
- LifecycleStateEnum lifecycleStateEnum = resource.getLifecycleState();
- if (lifecycleStateEnum == null) {
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
- }
- long currentDate = System.currentTimeMillis();
- if (resource.getCreationDate() == null) {
- resourceData.getMetadataDataDefinition().setCreationDate(currentDate);
- }
- resourceData.getMetadataDataDefinition().setLastUpdateDate(currentDate);
-
- return resourceData;
- }
-
- private ResourceMetadataData getResourceMetaDataForUpdate(Resource resource) {
- // PA - please note: if you add here any fields, make sure they are
- // validated (if needed)
- // at ResourceBusinessLogic.validateResourceFieldsBeforeUpdate() and
- // tested at ResourceBusinessLogicTest.
- ResourceMetadataData resourceData = getResourceMetaDataFromResource(resource);
- // resourceData.setLastUpdateDate(System.currentTimeMillis());
- // resourceData.setHighestVersion(resource.isHighestVersion());
- // resourceData.setNormalizedName(resource.getNormalizedName());
- // resourceData.setResourceType(resource.getResourceType().name());
-
- return resourceData;
- }
-
- public Either<Resource, StorageOperationStatus> getResource(String uniqueId) {
- return getResource(uniqueId, false);
- }
-
- public Either<Resource, StorageOperationStatus> getResource(String uniqueId, boolean inTransaction) {
- ComponentParametersView componentParametersView = new ComponentParametersView();
- return getResource(uniqueId, componentParametersView, inTransaction);
- }
-
- private TitanOperationStatus setComponentInstancesAttributesFromGraph(String uniqueId, Resource component) {
- Map<String, List<ComponentInstanceProperty>> resourceInstancesAttributes = new HashMap<>();
- TitanOperationStatus status = TitanOperationStatus.OK;
- List<ComponentInstance> componentInstances = component.getComponentInstances();
- if (componentInstances != null) {
- for (ComponentInstance resourceInstance : componentInstances) {
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> eitherRIAttributes = attributeOperation.getAllAttributesOfResourceInstance(resourceInstance);
- if (eitherRIAttributes.isRight()) {
- status = eitherRIAttributes.right().value();
- break;
- } else {
- resourceInstancesAttributes.put(resourceInstance.getUniqueId(), eitherRIAttributes.left().value());
- }
- }
-
- component.setComponentInstancesAttributes(resourceInstancesAttributes);
- }
-
- return status;
-
- }
-
- private StorageOperationStatus setResourceAdditionalInformationFromGraph(String uniqueId, Resource resource) {
-
- List<AdditionalInformationDefinition> additionalInformation = new ArrayList<>();
-
- Either<AdditionalInformationDefinition, StorageOperationStatus> either = additionalInformationOperation.getAllAdditionalInformationParameters(NodeTypeEnum.Resource, uniqueId, true, true);
-
- if (either.isRight()) {
- StorageOperationStatus status = either.right().value();
- if (status == StorageOperationStatus.NOT_FOUND) {
- return StorageOperationStatus.OK;
- }
- return status;
- }
-
- AdditionalInformationDefinition additionalInformationDefinition = either.left().value();
- additionalInformation.add(additionalInformationDefinition);
-
- resource.setAdditionalInformation(additionalInformation);
-
- return StorageOperationStatus.OK;
-
- }
-
- private StorageOperationStatus setResourceInterfacesFromGraph(String uniqueId, Resource resource) {
-
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> statusRes = interfaceLifecycleOperation.getAllInterfacesOfResource(uniqueId, true, true);
- if (statusRes.isRight()) {
- return statusRes.right().value();
- }
- Map<String, InterfaceDefinition> value = statusRes.left().value();
-
- resource.setInterfaces(value);
-
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus setResourceCapabilitiesFromGraph(String uniqueId, Resource resource) {
- StorageOperationStatus retStatus;
- Either<Map<String, CapabilityDefinition>, StorageOperationStatus> result = capabilityOperation.getAllCapabilitiesOfResource(uniqueId, true, true);
- if (result.isRight()) {
- StorageOperationStatus status = result.right().value();
- if (status != StorageOperationStatus.NOT_FOUND) {
- retStatus = status;
- } else {
- retStatus = StorageOperationStatus.OK;
- }
- } else {
- Map<String, CapabilityDefinition> capabilities = result.left().value();
- if (capabilities != null && !capabilities.isEmpty() && resource.getResourceType().equals(ResourceTypeEnum.VF)) {
- MigrationMalformedDataLogger.reportMalformedVF(resource.getUniqueId(), String.format("VF %s with id %s has direct capabilities.!!!!!!!!!!!!!", resource.getName(), resource.getUniqueId()));
- }
- if (capabilities == null || capabilities.isEmpty() || resource.getResourceType().equals(ResourceTypeEnum.VF)) {
- Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> eitherCapabilities = super.getCapabilities(resource, NodeTypeEnum.Resource, true);
- if (eitherCapabilities.isLeft()) {
- retStatus = StorageOperationStatus.OK;
- Map<String, List<CapabilityDefinition>> calculatedCapabilities = eitherCapabilities.left().value();
- resource.setCapabilities(calculatedCapabilities);
- } else {
- retStatus = StorageOperationStatus.GENERAL_ERROR;
- }
-
- } else {
- retStatus = StorageOperationStatus.OK;
- resource.setCapabilities(capabilityOperation.convertCapabilityMap(capabilities, null, null));
- }
-
- }
- return retStatus;
-
- }
-
- public Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> getCapabilities(org.openecomp.sdc.be.model.Component component, NodeTypeEnum componentTypeEnum, boolean inTransaction) {
-
- try {
- Either<Map<String, CapabilityDefinition>, StorageOperationStatus> result = capabilityOperation.getAllCapabilitiesOfResource(component.getUniqueId(), true, true);
- if (result.isRight() || result.left().value().isEmpty()) {
- final Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> eitherCapabilities = super.getCapabilities(component, componentTypeEnum, inTransaction);
- return eitherCapabilities;
- } else {
- return Either.left(capabilityOperation.convertCapabilityMap(result.left().value(), null, null));
- }
- } finally {
- if (inTransaction == false) {
- titanGenericDao.commit();
- }
- }
- }
-
- public Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> getRequirements(org.openecomp.sdc.be.model.Component component, NodeTypeEnum componentTypeEnum, boolean inTransaction) {
- try {
- Either<Map<String, RequirementDefinition>, StorageOperationStatus> result = requirementOperation.getAllResourceRequirements(component.getUniqueId(), true);
- if (result.isRight() || result.left().value().isEmpty()) {
- final Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> eitherCapabilities = super.getRequirements(component, componentTypeEnum, true);
- return eitherCapabilities;
- } else {
- return Either.left(requirementOperation.convertRequirementMap(result.left().value(), null, null));
- }
- } finally {
- if (inTransaction == false) {
- titanGenericDao.commit();
- }
- }
-
- }
-
- private StorageOperationStatus setResourceRequirementsFromGraph(String uniqueId, Resource resource, boolean inTransaction) {
- StorageOperationStatus retStatus;
- Either<Map<String, RequirementDefinition>, StorageOperationStatus> result = requirementOperation.getAllResourceRequirements(uniqueId, inTransaction);
- ;
- if (result.isRight()) {
- StorageOperationStatus status = result.right().value();
- if (status != StorageOperationStatus.NOT_FOUND) {
- retStatus = status;
- } else {
- retStatus = StorageOperationStatus.OK;
- }
- } else {
- Map<String, RequirementDefinition> requirements = result.left().value();
- if (requirements != null && !requirements.isEmpty() && resource.getResourceType().equals(ResourceTypeEnum.VF)) {
- MigrationMalformedDataLogger.reportMalformedVF(resource.getUniqueId(), String.format("VF %s with id %s has direct requirements.!!!!!!!!!!!!!", resource.getName(), resource.getUniqueId()));
- }
- if (requirements == null || requirements.isEmpty() || resource.getResourceType() == ResourceTypeEnum.VF) {
- Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> eitherCapabilities = super.getRequirements(resource, NodeTypeEnum.Resource, true);
- if (eitherCapabilities.isLeft()) {
- retStatus = StorageOperationStatus.OK;
- Map<String, List<RequirementDefinition>> calculatedCapabilities = eitherCapabilities.left().value();
- resource.setRequirements(calculatedCapabilities);
- } else {
- retStatus = StorageOperationStatus.GENERAL_ERROR;
- }
-
- } else {
- retStatus = StorageOperationStatus.OK;
- resource.setRequirements(requirementOperation.convertRequirementMap(requirements, null, null));
- }
-
- }
- return retStatus;
- }
-
- private TitanOperationStatus setResourcePropertiesFromGraph(String uniqueId, Resource resource) {
-
- List<PropertyDefinition> properties = new ArrayList<>();
- TitanOperationStatus status = propertyOperation.findAllResourcePropertiesRecursively(uniqueId, properties);
- if (status == TitanOperationStatus.OK) {
- resource.setProperties(properties);
- }
-
- return status;
-
- }
-
- private TitanOperationStatus setResourceAttributesFromGraph(String uniqueId, Resource resource) {
-
- List<PropertyDefinition> attributes = new ArrayList<>();
- TitanOperationStatus status = attributeOperation.findAllResourceAttributesRecursively(uniqueId, attributes);
- if (status == TitanOperationStatus.OK) {
- resource.setAttributes(attributes);
- }
-
- return status;
-
- }
-
- private TitanOperationStatus setResourceDerivedFromGraph(String uniqueId, Resource resource) {
- List<String> derivedFromList = new ArrayList<String>();
-
- TitanOperationStatus listFromGraphStatus = fillResourceDerivedListFromGraph(uniqueId, derivedFromList);
- if (!TitanOperationStatus.OK.equals(listFromGraphStatus)) {
- return listFromGraphStatus;
- }
-
- if (false == derivedFromList.isEmpty()) {
- if (derivedFromList.size() > 1) {
- List<String> lastDerivedFrom = new ArrayList<String>();
- lastDerivedFrom.add(derivedFromList.get(1));
- resource.setDerivedFrom(lastDerivedFrom);
- resource.setDerivedList(derivedFromList);
- } else {
- resource.setDerivedFrom(null);
- resource.setDerivedList(derivedFromList);
- }
-
- }
-
- return TitanOperationStatus.OK;
- }
-
- public TitanOperationStatus fillResourceDerivedListFromGraph(String uniqueId, List<String> derivedFromList) {
- // Either<List<ImmutablePair<ResourceMetadataData, GraphEdge>>,
- // TitanOperationStatus> childrenNodes =
- // titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource),
- // uniqueId, GraphEdgeLabels.DERIVED_FROM,
- // NodeTypeEnum.Resource, ResourceMetadataData.class);
- //
- // if (childrenNodes.isRight() && (childrenNodes.right().value() !=
- // TitanOperationStatus.NOT_FOUND)) {
- // return childrenNodes.right().value();
- // } else if (childrenNodes.isLeft()) {
- //
- // List<ImmutablePair<ResourceMetadataData, GraphEdge>> pairList =
- // childrenNodes.left().value();
- // for (ImmutablePair<ResourceMetadataData, GraphEdge> pair : pairList)
- // {
- // derivedFromList.add(pair.left.getMetadataDataDefinition().getName());
- // return
- // fillResourceDerivedListFromGraph(pair.left.getMetadataDataDefinition().getUniqueId(),
- // derivedFromList);
- // }
- // }
- List<ResourceMetadataData> derivedData = new ArrayList<ResourceMetadataData>();
- TitanOperationStatus findResourcesPathRecursively = findResourcesPathRecursively(uniqueId, derivedData);
- if (!findResourcesPathRecursively.equals(TitanOperationStatus.OK)) {
- return findResourcesPathRecursively;
- }
- derivedData.forEach(resourceData -> derivedFromList.add(((ResourceMetadataDataDefinition) resourceData.getMetadataDataDefinition()).getToscaResourceName()));
- return TitanOperationStatus.OK;
- }
-
- private TitanOperationStatus setResourceLastModifierFromGraph(Resource resource, String resourceId) {
-
- Either<ImmutablePair<UserData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.LAST_MODIFIER, NodeTypeEnum.User,
- UserData.class);
- if (parentNode.isRight()) {
- return parentNode.right().value();
- }
-
- ImmutablePair<UserData, GraphEdge> value = parentNode.left().value();
- if (log.isDebugEnabled())
- log.debug("Found parent node {}", value);
- UserData userData = value.getKey();
-
- if (log.isDebugEnabled())
- log.debug("Build resource : set last modifier userId to {}", userData.getUserId());
- String fullName = buildFullName(userData);
- if (log.isDebugEnabled())
- log.debug("Build resource : set last modifier full name to {}", fullName);
- resource.setLastUpdaterUserId(userData.getUserId());
- resource.setLastUpdaterFullName(fullName);
-
- return TitanOperationStatus.OK;
- }
-
- private TitanOperationStatus setResourceCreatorFromGraph(Resource resource, String resourceId) {
-
- Either<ImmutablePair<UserData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.CREATOR, NodeTypeEnum.User, UserData.class);
- if (parentNode.isRight()) {
- log.debug("Failed to find the creator of resource {}", resourceId);
- return parentNode.right().value();
- }
-
- ImmutablePair<UserData, GraphEdge> value = parentNode.left().value();
- if (log.isDebugEnabled())
- log.debug("Found parent node {}", value);
- UserData userData = value.getKey();
- if (log.isDebugEnabled())
- log.debug("Build resource : set creator userId to {}", userData.getUserId());
- String fullName = buildFullName(userData);
- if (log.isDebugEnabled())
- log.debug("Build resource : set creator full name to {}", fullName);
- resource.setCreatorUserId(userData.getUserId());
- resource.setCreatorFullName(fullName);
-
- return TitanOperationStatus.OK;
- }
-
- @Override
- TitanOperationStatus setComponentCategoriesFromGraph(Component resource) {
- String uniqueId = resource.getUniqueId();
- Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId, GraphEdgeLabels.CATEGORY,
- NodeTypeEnum.ResourceSubcategory, SubCategoryData.class);
- if (parentNode.isRight()) {
- return parentNode.right().value();
- }
-
- List<ImmutablePair<SubCategoryData, GraphEdge>> listValue = parentNode.left().value();
- log.debug("Result after looking for subcategory nodes pointed by resource {}. status is {}", uniqueId, listValue);
- if (listValue.size() > 1) {
- log.error("Multiple edges foud between resource {} to subcategory nodes.", uniqueId);
- }
- ImmutablePair<SubCategoryData, GraphEdge> value = listValue.get(0);
- log.debug("Found parent node {}", value);
-
- SubCategoryData subcategoryData = value.getKey();
-
- Either<ImmutablePair<CategoryData, GraphEdge>, TitanOperationStatus> categoryNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory), (String) subcategoryData.getUniqueId(),
- GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceNewCategory, CategoryData.class);
- if (categoryNode.isRight()) {
- return categoryNode.right().value();
- }
-
- CategoryData categoryData = categoryNode.left().value().left;
- CategoryDefinition catDef = new CategoryDefinition(categoryData.getCategoryDataDefinition());
- SubCategoryDefinition subcatDef = new SubCategoryDefinition(subcategoryData.getSubCategoryDataDefinition());
-
- resource.addCategory(catDef, subcatDef);
- return TitanOperationStatus.OK;
- }
-
- public String buildFullName(UserData userData) {
-
- String fullName = userData.getFirstName();
- if (fullName == null) {
- fullName = "";
- } else {
- fullName = fullName + " ";
- }
- String lastName = userData.getLastName();
- if (lastName != null) {
- fullName += lastName;
- }
- return fullName;
- }
-
- private Resource convertResourceDataToResource(ResourceMetadataData resourceData) {
-
- ResourceMetadataDefinition resourceMetadataDataDefinition = new ResourceMetadataDefinition((ResourceMetadataDataDefinition) resourceData.getMetadataDataDefinition());
-
- Resource resource = new Resource(resourceMetadataDataDefinition);
-
- return resource;
- }
-
- @Override
- public Either<Resource, StorageOperationStatus> deleteResource(String resourceId) {
- return deleteResource(resourceId, false);
- }
-
- @Override
- public Either<Resource, StorageOperationStatus> updateResource(Resource resource) {
-
- return updateResource(resource, false);
-
- }
-
- @Override
- public Either<Integer, StorageOperationStatus> getNumberOfResourcesByName(String resourceName) {
-
- Map<String, Object> propertiesToMatch = new HashMap<String, Object>();
- propertiesToMatch.put(GraphPropertiesDictionary.NAME.getProperty(), resourceName);
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> getParentResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class);
- log.debug("result after searching for resources called {} is {}", resourceName, getParentResources);
- if (getParentResources.isRight()) {
- TitanOperationStatus titanStatus = getParentResources.right().value();
- if (titanStatus == TitanOperationStatus.NOT_FOUND) {
- log.debug("Number of returned resources is 0.");
- return Either.left(0);
- }
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus));
- } else {
- List<ResourceMetadataData> value = getParentResources.left().value();
- int numberOFResources = (value == null ? 0 : value.size());
- log.debug("The number of resources returned after searching for resource called {} is {}", resourceName, numberOFResources);
- return Either.left(numberOFResources);
- }
- }
-
- public PropertyOperation getPropertyOperation() {
- return propertyOperation;
- }
-
- public void setPropertyOperation(PropertyOperation propertyOperation) {
- this.propertyOperation = propertyOperation;
- }
-
- public RequirementOperation getRequirementOperation() {
- return requirementOperation;
- }
-
- public void setRequirementOperation(RequirementOperation requirementOperation) {
- this.requirementOperation = requirementOperation;
- }
-
- public CapabilityOperation getCapabilityOperation() {
- return capabilityOperation;
- }
-
- public void setCapabilityOperation(CapabilityOperation capabilityOperation) {
- this.capabilityOperation = capabilityOperation;
- }
-
- public IArtifactOperation getArtifactOperation() {
- return artifactOperation;
- }
-
- public void setArtifactOperation(IArtifactOperation artifactOperation) {
- this.artifactOperation = artifactOperation;
- }
-
- public InterfaceLifecycleOperation getInterfaceLifecycleOperation() {
- return interfaceLifecycleOperation;
- }
-
- public void setInterfaceLifecycleOperation(InterfaceLifecycleOperation interfaceLifecycleOperation) {
- this.interfaceLifecycleOperation = interfaceLifecycleOperation;
- }
-
- public TitanGenericDao getTitanGenericDao() {
- return titanGenericDao;
- }
-
- public IElementOperation getElementOperation() {
- return elementOperation;
- }
-
- public void setElementOperation(IElementOperation elementOperation) {
- this.elementOperation = elementOperation;
- }
-
- /**
- * FOR TEST ONLY
- *
- * @param titanGenericDao
- */
- public void setTitanGenericDao(TitanGenericDao titanGenericDao) {
- this.titanGenericDao = titanGenericDao;
- }
-
- @Override
- public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract) {
-
- return getAllCertifiedResources(isAbstract, null);
-
- }
-
- @Override
- /**
- * Deletes the resource node, property nodes and relation to artifacts. MUST handle deletion of artifact from artifacts repository outside this method (in catalog-be)
- */
- public Either<Resource, StorageOperationStatus> deleteResource(String resourceId, boolean inTransaction) {
-
- Either<Resource, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR);
- try {
-
- Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
- if (graphResult.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
- return result;
- }
-
- TitanGraph titanGraph = graphResult.left().value();
- Iterable<TitanVertex> vertecies = titanGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId).vertices();
- Either<Resource, StorageOperationStatus> resourceEither = getResource(resourceId, true);
- Resource resource = resourceEither.left().value();
- if (vertecies != null && resourceEither.isLeft()) {
- Iterator<TitanVertex> iterator = vertecies.iterator();
- if (iterator != null && iterator.hasNext()) {
- Vertex rootVertex = iterator.next();
- TitanOperationStatus deleteChildrenNodes = graphDeleteUtil.deleteChildrenNodes(rootVertex, GraphEdgeLabels.PROPERTY);
- log.debug("After deleting properties nodes in the graph. status is {}", deleteChildrenNodes);
- if (deleteChildrenNodes != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteChildrenNodes));
- return result;
- }
- StorageOperationStatus removeInterfacesFromResource = removeInterfacesFromResource(resource);
- log.debug("After deleting interfaces nodes in the graph. status is {}", removeInterfacesFromResource);
- if (!removeInterfacesFromResource.equals(StorageOperationStatus.OK)) {
- result = Either.right(removeInterfacesFromResource);
- return result;
- }
- StorageOperationStatus removeArtifactsFromResource = removeArtifactsFromResource(resource);
- log.debug("After deleting artifacts nodes in the graph. status is {}", removeArtifactsFromResource);
- if (!removeArtifactsFromResource.equals(StorageOperationStatus.OK)) {
- result = Either.right(removeArtifactsFromResource);
- return result;
- }
- StorageOperationStatus removeCapabilitiesFromResource = removeCapabilitiesFromResource(resource);
- log.debug("After deleting capabilities nodes in the graph. status is {}", removeCapabilitiesFromResource);
- if (!removeCapabilitiesFromResource.equals(StorageOperationStatus.OK)) {
- result = Either.right(removeCapabilitiesFromResource);
- return result;
- }
-
- StorageOperationStatus removeRequirementsFromResource = removeRequirementsFromResource(resource);
- log.debug("After deleting requirements nodes in the graph. status is {}", removeRequirementsFromResource);
- if (!removeRequirementsFromResource.equals(StorageOperationStatus.OK)) {
- result = Either.right(removeRequirementsFromResource);
- return result;
- }
-
- StorageOperationStatus removeRIsFromResource = removeResourceInstanceFromResource(resource);
- log.debug("After deleting resource instance nodes in the graph. status is {}", removeRIsFromResource);
- if (!removeRIsFromResource.equals(StorageOperationStatus.OK)) {
- result = Either.right(removeRIsFromResource);
- return result;
- }
-
- StorageOperationStatus removeAttributesFromResource = removeAttributesFromResource(resource);
- log.debug("After deleting requirements nodes in the graph. status is {}", removeRequirementsFromResource);
- if (removeAttributesFromResource != StorageOperationStatus.OK) {
- result = Either.right(removeAttributesFromResource);
- return result;
- }
-
- StorageOperationStatus removeInputsFromResource = removeInputsFromComponent(NodeTypeEnum.Resource, resource);
- log.debug("After deleting requirements nodes in the graph. status is {}", removeInputsFromResource);
- if (removeInputsFromResource != StorageOperationStatus.OK) {
- result = Either.right(removeInputsFromResource);
- return result;
- }
-
- StorageOperationStatus removeAdditionalInformationFromResource = super.deleteAdditionalInformation(NodeTypeEnum.Resource, resource.getUniqueId());
- log.debug("After deleting additional information node in the graph. status is {}", removeAdditionalInformationFromResource);
- if (!removeAdditionalInformationFromResource.equals(StorageOperationStatus.OK)) {
- result = Either.right(removeAdditionalInformationFromResource);
- return result;
- }
-
- StorageOperationStatus removeGroupsFromResource = super.deleteGroups(NodeTypeEnum.Resource, resource.getUniqueId());
- log.debug("After deleting group nodes in the graph. status is {}", removeGroupsFromResource);
- if (!removeGroupsFromResource.equals(StorageOperationStatus.OK)) {
- result = Either.right(removeGroupsFromResource);
- return result;
- }
-
- rootVertex.remove();
-
- } else {
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- return result;
- }
- } else {
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- return result;
- }
-
- result = Either.left(resource);
- return result;
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("deleteResource operation : Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("deleteResource operation : Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- private StorageOperationStatus removeAttributesFromResource(Resource resource) {
- Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllAttributeAssociatedToNode = attributeOperation.deleteAllAttributeAssociatedToNode(NodeTypeEnum.Resource, resource.getUniqueId());
- return deleteAllAttributeAssociatedToNode.isRight() ? deleteAllAttributeAssociatedToNode.right().value() : StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus removeArtifactsFromResource(Resource resource) {
-
- String resourceId = resource.getUniqueId();
- Map<String, ArtifactDefinition> allArtifacts = new HashMap<String, ArtifactDefinition>();
- if (resource.getArtifacts() != null) {
- allArtifacts.putAll(resource.getArtifacts());
- }
- if (resource.getDeploymentArtifacts() != null) {
- allArtifacts.putAll(resource.getDeploymentArtifacts());
- }
- if (allArtifacts != null) {
- for (Entry<String, ArtifactDefinition> entry : allArtifacts.entrySet()) {
-
- ArtifactDefinition artifactDefinition = entry.getValue();
- Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource = artifactOperation.removeArifactFromResource(resourceId, artifactDefinition.getUniqueId(), NodeTypeEnum.Resource, true, true);
- if (removeArifactFromResource.isRight()) {
- return removeArifactFromResource.right().value();
- }
- }
- }
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus removeInterfacesFromResource(Resource resource) {
-
- String resourceId = resource.getUniqueId();
- // delete only interfaces of this resource (not interfaces derived)
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(resourceId, false, true);
- if (allInterfacesOfResource.isRight()) {
- log.error("failed to get interfaces for resource {}. status is {}", resourceId, allInterfacesOfResource.right().value());
- return allInterfacesOfResource.right().value();
- }
- Map<String, InterfaceDefinition> interfaces = allInterfacesOfResource.left().value();
- if (interfaces != null) {
- for (Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
- Boolean isAbstract = resource.isAbstract();
-
- InterfaceDefinition interfaceDefinition = entry.getValue();
- // esofer - in case the resource is abstract, we deleting only
- // the edge to the interface.
- if (isAbstract != null && true == isAbstract.booleanValue()) {
- log.debug("Going to dissociate resource {} from interface {}", resourceId, interfaceDefinition.getUniqueId());
- UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.Resource, resourceId);
- Either<InterfaceDefinition, StorageOperationStatus> dissociateInterfaceFromNode = interfaceLifecycleOperation.dissociateInterfaceFromNode(uniqueIdData, interfaceDefinition);
- if (dissociateInterfaceFromNode.isRight()) {
- log.error("failed to dissociate resource {} from interface {}. status is {}", resourceId, interfaceDefinition.getUniqueId(), dissociateInterfaceFromNode.right().value());
- return dissociateInterfaceFromNode.right().value();
- }
- } else {
- Either<InterfaceDefinition, StorageOperationStatus> deleteInterfaceOfResourceOnGraph = interfaceLifecycleOperation.deleteInterfaceOfResourceOnGraph(resourceId, interfaceDefinition, true);
- if (deleteInterfaceOfResourceOnGraph.isRight()) {
- return deleteInterfaceOfResourceOnGraph.right().value();
- }
- }
- }
- }
- return StorageOperationStatus.OK;
- }
-
- private StorageOperationStatus removeCapabilitiesFromResource(Resource resource) {
-
- String resourceId = resource.getUniqueId();
-
- Either<Map<String, CapabilityDefinition>, StorageOperationStatus> deleteAllRes = capabilityOperation.deleteAllCapabilities(resourceId, true);
- if (deleteAllRes.isRight()) {
- StorageOperationStatus status = deleteAllRes.right().value();
- if (status == StorageOperationStatus.NOT_FOUND) {
- return StorageOperationStatus.OK;
- }
- return status;
- }
-
- return StorageOperationStatus.OK;
-
- }
-
- private StorageOperationStatus removeRequirementsFromResource(Resource resource) {
-
- String resourceId = resource.getUniqueId();
-
- Either<Map<String, RequirementDefinition>, StorageOperationStatus> deleteAllRes = requirementOperation.deleteAllRequirements(resourceId, true);
-
- if (deleteAllRes.isRight()) {
- StorageOperationStatus status = deleteAllRes.right().value();
- if (status == StorageOperationStatus.NOT_FOUND) {
- return StorageOperationStatus.OK;
- }
- return status;
- }
-
- return StorageOperationStatus.OK;
-
- }
-
- private StorageOperationStatus removeResourceInstanceFromResource(Resource resource) {
- String resourceId = resource.getUniqueId();
-
- Either<List<ComponentInstance>, StorageOperationStatus> deleteAllResourceInstancesRes = componentInstanceOperation.deleteAllComponentInstances(resourceId, NodeTypeEnum.Resource, true);
- if (deleteAllResourceInstancesRes.isRight()) {
- StorageOperationStatus status = deleteAllResourceInstancesRes.right().value();
- if (status == StorageOperationStatus.NOT_FOUND) {
- return StorageOperationStatus.OK;
- }
- return status;
- }
- return StorageOperationStatus.OK;
- }
-
- @Override
- public Either<Resource, StorageOperationStatus> updateResource(Resource resource, boolean inTransaction) {
- return (Either<Resource, StorageOperationStatus>) updateComponent(resource, inTransaction, titanGenericDao, resource.getClass(), NodeTypeEnum.Resource);
-
- }
-
- @Override
- protected <T extends Component> StorageOperationStatus updateDerived(Component component, Component currentComponent, ComponentMetadataData updatedResourceData, Class<T> clazz) {
- Resource resource = (Resource) component;
- Resource currentResource = (Resource) currentComponent;
- if (resource.getDerivedFrom() != null) {// meaning derived from changed
-
- Either<List<ResourceMetadataData>, StorageOperationStatus> findDerivedResourcesOld = findDerivedResources(currentResource);
- if (findDerivedResourcesOld.isRight()) {
- log.debug("Couldn't find derived resource {} for current resource in the graph", currentResource.getDerivedFrom().get(0));
- return findDerivedResourcesOld.right().value();
- }
-
- List<ResourceMetadataData> oldDerived = findDerivedResourcesOld.left().value();
- if (oldDerived.isEmpty()) {
- log.debug("Derived from list fetched from DB for current resource is empty");
- return StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND;
- }
-
- Either<List<ResourceMetadataData>, StorageOperationStatus> findDerivedResourcesNew = findDerivedResources((Resource) resource);
- if (findDerivedResourcesNew.isRight()) {
- log.debug("Couldn't find derived resource {} for update resource in the graph", resource.getDerivedFrom().get(0));
- return findDerivedResourcesNew.right().value();
- }
-
- List<ResourceMetadataData> newDerived = findDerivedResourcesNew.left().value();
- if (newDerived.isEmpty()) {
- log.debug("Derived from list fetched from DB for updated resource is empty");
- return StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND;
- }
-
- Either<Boolean, TitanOperationStatus> reassociateDerivedFrom = reassociateDerivedFrom((ResourceMetadataData) updatedResourceData, oldDerived, newDerived);
- if (reassociateDerivedFrom.isRight()) {
- log.debug("Couldn't change derived from for the resoure");
- return DaoStatusConverter.convertTitanStatusToStorageStatus(reassociateDerivedFrom.right().value());
- }
- }
- return StorageOperationStatus.OK;
- }
-
- private Either<Boolean, TitanOperationStatus> reassociateDerivedFrom(ResourceMetadataData resourceData, List<ResourceMetadataData> oldDerived, List<ResourceMetadataData> newDerived) {
- ResourceMetadataData oldDerivedNode = oldDerived.get(0);
- log.debug("Dissociating resource {} from old parent resource {}", resourceData.getUniqueId(), oldDerivedNode.getUniqueId());
- Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(resourceData, oldDerivedNode, GraphEdgeLabels.DERIVED_FROM);
- if (deleteRelation.isRight()) {
- log.debug("Failed to dissociate resource {} from old parent resource {}", resourceData.getUniqueId(), oldDerivedNode.getUniqueId());
- return Either.right(deleteRelation.right().value());
- }
- ResourceMetadataData newDerivedNode = newDerived.get(0);
- log.debug("Associating resource {} with new parent resource {}", resourceData.getUniqueId(), newDerivedNode.getUniqueId());
- Either<GraphRelation, TitanOperationStatus> addRelation = titanGenericDao.createRelation(resourceData, newDerivedNode, GraphEdgeLabels.DERIVED_FROM, null);
- if (addRelation.isRight()) {
- log.debug("Failed to associate resource {} with new parent resource {}", resourceData.getUniqueId(), newDerivedNode.getUniqueId());
- return Either.right(addRelation.right().value());
- }
-
- return Either.left(true);
- }
-
- private StorageOperationStatus moveCategoryEdge(Resource resource, ResourceMetadataData resourceData, CategoryDefinition newCategory) {
-
- StorageOperationStatus result = StorageOperationStatus.OK;
-
- GraphRelation categoryRelation = new GraphRelation();
- categoryRelation.setType(GraphEdgeLabels.CATEGORY.getProperty());
- RelationEndPoint relationEndPoint = new RelationEndPoint(NodeTypeEnum.Resource, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId());
- categoryRelation.setFrom(relationEndPoint);
- Either<GraphRelation, TitanOperationStatus> deleteOutgoingRelation = titanGenericDao.deleteOutgoingRelation(categoryRelation);
- if (deleteOutgoingRelation.isRight()) {
- log.error("Failed to delete category from resource {}. Edge type is {}", resourceData.getUniqueId(), GraphEdgeLabels.CATEGORY);
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteOutgoingRelation.right().value());
- return result;
- }
-
- log.debug("After removing edge from graph {}", deleteOutgoingRelation);
-
- return assosiateMetadataToCategory(resource, resourceData);
- }
-
- private StorageOperationStatus moveLastModifierEdge(Resource resource, ResourceMetadataData resourceData, UserData modifierUserData) {
-
- StorageOperationStatus result = StorageOperationStatus.OK;
-
- GraphRelation lastModifierRelation = new GraphRelation();
- lastModifierRelation.setType(GraphEdgeLabels.LAST_MODIFIER.getProperty());
- RelationEndPoint relationEndPoint = new RelationEndPoint(NodeTypeEnum.Resource, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId());
- lastModifierRelation.setTo(relationEndPoint);
- Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = titanGenericDao.deleteIncomingRelation(lastModifierRelation);
- if (deleteIncomingRelation.isRight()) {
- log.error("Failed to delete user from resource {}. Edge type is {}", resourceData.getUniqueId(),GraphEdgeLabels.LAST_MODIFIER);
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteIncomingRelation.right().value());
- return result;
- }
-
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(modifierUserData, resourceData, GraphEdgeLabels.LAST_MODIFIER, null);
- log.debug("After associating user {} to resource {}. Edge type is {}", modifierUserData, resourceData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
- if (createRelation.isRight()) {
- log.error("Failed to associate user {} to resource {}. Edge type is {}", modifierUserData, resourceData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER);
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value());
- return result;
- }
-
- return result;
- }
-
- private Either<ResourceMetadataData, TitanOperationStatus> findResource(String resourceId) {
-
- String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource);
- Either<ResourceMetadataData, TitanOperationStatus> findResource = titanGenericDao.getNode(key, resourceId, ResourceMetadataData.class);
-
- return findResource;
- }
-
- private StorageOperationStatus setArtifactFromGraph(String uniqueId, Resource resource) {
- StorageOperationStatus result = StorageOperationStatus.OK;
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(uniqueId, NodeTypeEnum.Resource, true);
- if (artifacts.isRight()) {
- result = artifacts.right().value();
- } else {
- createSpecificArtifactList(resource, artifacts.left().value());
- }
- return result;
- }
-
- @Override
- public <T extends Component> Either<T, StorageOperationStatus> getComponent(String id, Class<T> clazz) {
-
- Either<Resource, StorageOperationStatus> component = getResource(id);
- if (component.isRight()) {
- return Either.right(component.right().value());
- }
- return Either.left(clazz.cast(component.left().value()));
- }
-
- @Override
- public Either<Boolean, StorageOperationStatus> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceType) {
- if (resourceType != null) {
- Map<String, Object> properties = new HashMap<String, Object>();
- properties.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
- if (resourceType.equals(ResourceTypeEnum.VF)) {
- return validateResourceNameUniqueness(resourceName, properties, null, titanGenericDao);
- } else {
- return validateResourceNameUniqueness(resourceName, null, properties, titanGenericDao);
- }
-
- } else {
- return validateResourceNameUniqueness(resourceName, null, null, titanGenericDao);
- }
-
- }
-
- public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
- return validateToscaResourceNameUniqueness(templateName, titanGenericDao);
- }
-
- //Tal G for US815447
- public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
-
- String currentTemplateNameChecked = templateNameExtends;
-
- while(currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)){
- Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked, true);
-
- if(latestByToscaResourceName.isRight()){
- return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
- }
-
- Resource value = latestByToscaResourceName.left().value();
-
- if(value.getDerivedFrom() != null){
- currentTemplateNameChecked = value.getDerivedFrom().get(0);
- } else {
- currentTemplateNameChecked = null;
- }
- }
-
- return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
- }
-
- public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) {
- List<ArtifactDefinition> artifacts = new ArrayList<>();
-
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> interfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(resourceId, false, true);
- if (interfacesOfResource.isRight()) {
- log.error("failed to get all resource interfaces. resource id={}. status ={}", resourceId, interfacesOfResource.right().value());
- return Either.right(interfacesOfResource.right().value());
- }
-
- Map<String, InterfaceDefinition> interfaces = interfacesOfResource.left().value();
- if (interfaces != null && !interfaces.isEmpty()) {
- for (Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
-
- InterfaceDefinition interfaceDefinition = entry.getValue();
- Map<String, Operation> operations = interfaceDefinition.getOperationsMap();
- if (operations != null && !operations.isEmpty()) {
- for (Entry<String, Operation> opEntry : operations.entrySet()) {
-
- Operation operation = opEntry.getValue();
- ArtifactDefinition artifactDefinition = operation.getImplementationArtifact();
- if (artifactDefinition != null) {
- artifacts.add(artifactDefinition);
- }
- }
- }
- }
- }
- return Either.left(artifacts);
- }
-
- @SuppressWarnings("unchecked")
- public Either<List<Resource>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction) {
- return (Either<List<Resource>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getFollowedComponent(userId, lifecycleStates, lastStateStates, inTransaction, titanGenericDao, NodeTypeEnum.Resource);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> Either<T, StorageOperationStatus> getComponent(String id, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) getResource(id, inTransaction);
- }
-
- // @Override
- // public <T> Either<T, StorageOperationStatus> getComponent_tx(String id,
- // boolean inTransaction) {
- // return (Either<T, StorageOperationStatus>) getResource_tx(id,
- // inTransaction);
- // }
-
- private Optional<ImmutablePair<SubCategoryData, GraphEdge>> validateCategoryHierarcy(List<ImmutablePair<SubCategoryData, GraphEdge>> childNodes, String subCategoryName) {
- Predicate<ImmutablePair<SubCategoryData, GraphEdge>> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName);
- return childNodes.stream().filter(matchName).findAny();
- }
-
- private Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> getAllSubCategories(String categoryName) {
- Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class);
- if (categoryResult.isRight()) {
- return Either.right(categoryResult.right().value());
- }
- CategoryData categoryData = categoryResult.left().value();
-
- Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(),
- GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class);
- if (childrenNodes.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenNodes.right().value()));
- }
- return Either.left(childrenNodes.left().value());
- }
-
- @Override
- public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
-
- String subCategoryName = filters.get(FilterKeyEnum.SUB_CATEGORY);
- String categoryName = filters.get(FilterKeyEnum.CATEGORY);
- ResourceTypeEnum resourceType = ResourceTypeEnum.getType( filters.get(FilterKeyEnum.RESOURCE_TYPE));
- Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> subcategories = null;
- Optional<ImmutablePair<SubCategoryData, GraphEdge>> subCategoryData;
-
- if (categoryName != null) {
- subcategories = getAllSubCategories(categoryName);
- if (subcategories.isRight()) {
- filters.remove(FilterKeyEnum.SUB_CATEGORY);
- return Either.right(subcategories.right().value());
- }
- }
- if (subCategoryName != null) { // primary filter
- if (categoryName != null) {
- subCategoryData = validateCategoryHierarcy(subcategories.left().value(), subCategoryName);
- if (!subCategoryData.isPresent()) {
- return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
- }
- return fetchByCategoryOrSubCategoryUid((String) subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction,
- ResourceMetadataData.class, resourceType);
- }
-
- return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType);
- }
- if(subcategories != null){
- return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType);
- }
- return fetchByResourceType(NodeTypeEnum.Resource, filters.get(FilterKeyEnum.RESOURCE_TYPE), ResourceMetadataData.class, inTransaction);
- }
-
- @SuppressWarnings("unchecked")
- private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByResourceType(NodeTypeEnum nodeType, String resourceType,
- Class<S> clazz, boolean inTransaction) {
- List<T> components = null;
- TitanOperationStatus status;
- Wrapper<StorageOperationStatus> statusWrapper = new Wrapper<>();
- Either<List<T>, StorageOperationStatus> result;
- try {
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType);
- props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
- Either<List<S>, TitanOperationStatus> getResources = titanGenericDao.getByCriteria(nodeType, props, clazz);
- if (getResources.isRight()) {
- status = getResources.right().value();
- if(status != TitanOperationStatus.NOT_FOUND){
- statusWrapper.setInnerElement(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }else{
- components = new ArrayList<>();
- }
- }else{
- components = getResources.left().value().stream().
- map(c->(T)convertComponentMetadataDataToComponent(c)).collect(Collectors.toList());
- }
- if(!statusWrapper.isEmpty()){
- result = Either.right(statusWrapper.getInnerElement());
- }else{
- result = Either.left(components);
- }
- return result;
- } finally {
- if (!inTransaction) {
- titanGenericDao.commit();
- }
- }
- }
-
- private <T> Either<List<T>, StorageOperationStatus> fetchByMainCategory(List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) {
- List<T> components = new ArrayList<>();
-
- for (ImmutablePair<SubCategoryData, GraphEdge> subCategory : subcategories) {
- Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource,
- inTransaction, ResourceMetadataData.class, resourceType);
- if (fetched.isRight()) {
- // return fetched;
- continue;
- }
- components.addAll(fetched.left().value());
- }
- return Either.left(components);
- }
-
- @Override
- public <T> Either<T, StorageOperationStatus> getLightComponent(String id, boolean inTransaction) {
- return getLightComponent(id, NodeTypeEnum.Resource, inTransaction);
- }
-
- // will be implement later
- @Override
- protected ComponentMetadataData getMetaDataFromComponent(Component component) {
- return getResourceMetaDataFromResource((Resource) component);
- }
-
- @Override
- public Either<Set<Resource>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch, boolean inTransaction) {
- return getComponentCatalogData(NodeTypeEnum.Resource, propertiesToMatch, Resource.class, ResourceMetadataData.class, inTransaction);
- }
-
- @Override
- public Either<List<Resource>, StorageOperationStatus> getAllDerivedResources(Resource resource) {
- try {
- Either<List<ImmutablePair<ResourceMetadataData, GraphEdge>>, TitanOperationStatus> childrenNodes = getDerivingChildren(resource);
- return childrenNodes.either((childrenPairs) -> convertToResources(PairUtils.leftSequence(childrenPairs)),
- (status) -> Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)));
- } finally {
- titanGenericDao.commit();
- }
- }
-
- @Override
- public Either<List<Resource>, StorageOperationStatus> getRootResources() {
- Map<String, Object> rootToscaResource = new HashMap<>();
- rootToscaResource.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), Resource.ROOT_RESOURCE);
- return getResourceListByCriteria(rootToscaResource, false);
- }
-
- @Override
- public Either<List<Resource>, StorageOperationStatus> getVFResources() {
- Map<String, Object> rootToscaResource = new HashMap<>();
- rootToscaResource.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF);
- return getResourceListByCriteria(rootToscaResource, false);
- }
-
- private Either<List<ImmutablePair<ResourceMetadataData, GraphEdge>>, TitanOperationStatus> getDerivingChildren(Resource resource) {
- return titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class);
- }
-
- private Either<List<Resource>, StorageOperationStatus> convertToResources(List<ResourceMetadataData> resourcesMetaData) {
- List<Resource> resources = new ArrayList<>();
- for (ResourceMetadataData resourceMetadataData : resourcesMetaData) {
- String uniqueId = resourceMetadataData.getMetadataDataDefinition().getUniqueId();
- Either<Resource, StorageOperationStatus> resource = this.getResource(uniqueId);
- if (resource.isRight()) {
- StorageOperationStatus status = resource.right().value();
- log.error("Failed to fetch resource {} . status is {}", uniqueId, status);
- return Either.right(status);
- }
- resources.add(resource.left().value());
- }
- return Either.left(resources);
- }
-
- protected TitanOperationStatus findResourcesPathRecursively(String resourceId, List<ResourceMetadataData> resourcesPathList) {
-
- Either<ResourceMetadataData, TitanOperationStatus> nodeRes = this.titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, ResourceMetadataData.class);
-
- if (nodeRes.isRight()) {
- TitanOperationStatus status = nodeRes.right().value();
- log.error("Failed to fetch resource {} . status is {}", resourceId, status);
- return status;
- }
-
- ResourceMetadataData resourceData = nodeRes.left().value();
- resourcesPathList.add(resourceData);
- Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentResourceRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM,
- NodeTypeEnum.Resource, ResourceMetadataData.class);
-
- while (parentResourceRes.isLeft()) {
-
- ImmutablePair<ResourceMetadataData, GraphEdge> value = parentResourceRes.left().value();
- ResourceMetadataData parentResourceData = value.getKey();
-
- resourcesPathList.add(parentResourceData);
-
- parentResourceRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), parentResourceData.getMetadataDataDefinition().getUniqueId(), GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource,
- ResourceMetadataData.class);
- }
-
- TitanOperationStatus operationStatus = parentResourceRes.right().value();
-
- if (operationStatus != TitanOperationStatus.NOT_FOUND) {
- return operationStatus;
- } else {
- return TitanOperationStatus.OK;
- }
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> Either<T, StorageOperationStatus> updateComponent(T component, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) updateResource((Resource) component, inTransaction);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Either<Component, StorageOperationStatus> deleteComponent(String id, boolean inTransaction) {
- return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteResource(id, inTransaction);
- }
-
- @Override
- public Either<Resource, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName, boolean inTransaction) {
- return getLatestByName(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), toscaResourceName, inTransaction);
-
- }
-
- @Override
- public Either<Resource, StorageOperationStatus> getLatestByName(String resourceName, boolean inTransaction) {
- return getLatestByName(GraphPropertiesDictionary.NAME.getProperty(), resourceName, inTransaction);
-
- }
-
- private Either<Resource, StorageOperationStatus> getLatestByName(String property, String resourceName, boolean inTransaction) {
- Either<Resource, StorageOperationStatus> result = null;
- try {
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(property, resourceName);
- props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> highestResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
- if (highestResources.isRight()) {
- TitanOperationStatus status = highestResources.right().value();
- log.debug("failed to find resource with name {}. status={} ", resourceName, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- List<ResourceMetadataData> resources = highestResources.left().value();
- double version = 0.0;
- ResourceMetadataData highestResource = null;
- for (ResourceMetadataData resource : resources) {
- double resourceVersion = Double.parseDouble(resource.getMetadataDataDefinition().getVersion());
- if (resourceVersion > version) {
- version = resourceVersion;
- highestResource = resource;
- }
- }
- result = getResource(highestResource.getMetadataDataDefinition().getUniqueId(), true);
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("getLatestByName operation : Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("getLatestByName operation : Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
-
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Either<List<Resource>, StorageOperationStatus> getTesterFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction) {
- return (Either<List<Resource>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getTesterFollowedComponent(userId, lifecycleStates, inTransaction, NodeTypeEnum.Resource);
- }
-
- @Override
- public Either<List<Resource>, StorageOperationStatus> getResourceCatalogData(boolean inTransaction) {
- return getResourceCatalogData(inTransaction, null);
- }
-
- private Either<List<Resource>, StorageOperationStatus> getResourceCatalogData(boolean inTransaction, Map<String, Object> otherToMatch) {
-
- long start = System.currentTimeMillis();
-
- long startFetchAllStates = System.currentTimeMillis();
- Map<String, Object> propertiesToMatchHigest = new HashMap<>();
- propertiesToMatchHigest.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
- propertiesToMatchHigest.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), false);
- Either<List<ResourceMetadataData>, TitanOperationStatus> allHighestStates = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatchHigest, ResourceMetadataData.class);
- if (allHighestStates.isRight() && allHighestStates.right().value() != TitanOperationStatus.NOT_FOUND) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allHighestStates.right().value()));
- }
-
- if (allHighestStates.isRight()) {
- return Either.left(new ArrayList<>());
- }
- List<ResourceMetadataData> list = allHighestStates.left().value();
-
- List<ResourceMetadataData> certified = new ArrayList<>();
- List<ResourceMetadataData> noncertified = new ArrayList<>();
- for (ResourceMetadataData reData : list) {
- if (reData.getMetadataDataDefinition().getState().equals(LifecycleStateEnum.CERTIFIED.name())) {
- certified.add(reData);
- } else {
- noncertified.add(reData);
- }
- }
-
- long endFetchAll = System.currentTimeMillis();
- log.debug("Fetch catalog resources all states: certified {}, noncertified {}", certified.size(), noncertified.size());
- log.debug("Fetch catalog resources all states from graph took {} ms", endFetchAll - startFetchAllStates);
-
- try {
- List<ResourceMetadataData> notCertifiedHighest = noncertified;
- List<ResourceMetadataData> certifiedHighestList = certified;
-
- HashMap<String, String> VFNames = new HashMap<>();
- HashMap<String, String> VFCNames = new HashMap<>();
- for (ResourceMetadataData data : notCertifiedHighest) {
- String serviceName = data.getMetadataDataDefinition().getName();
- if (((ResourceMetadataDataDefinition) data.getMetadataDataDefinition()).getResourceType().equals(ResourceTypeEnum.VF)) {
- VFNames.put(serviceName, serviceName);
- } else {
- VFCNames.put(serviceName, serviceName);
- }
- }
-
- for (ResourceMetadataData data : certifiedHighestList) {
- String serviceName = data.getMetadataDataDefinition().getName();
- if (((ResourceMetadataDataDefinition) data.getMetadataDataDefinition()).getResourceType().equals(ResourceTypeEnum.VF)) {
- if (!VFNames.containsKey(serviceName)) {
- notCertifiedHighest.add(data);
- }
- } else {
- if (!VFCNames.containsKey(serviceName)) {
- notCertifiedHighest.add(data);
- }
- }
- }
-
- long endFetchAllFromGraph = System.currentTimeMillis();
- log.debug("Fetch all catalog resources metadata from graph took {} ms", endFetchAllFromGraph - start);
-
- long startFetchAllFromCache = System.currentTimeMillis();
-
- List<Resource> result = new ArrayList<>();
-
- Map<String, Long> components = notCertifiedHighest.stream().collect(Collectors.toMap(p -> p.getMetadataDataDefinition().getUniqueId(), p -> p.getMetadataDataDefinition().getLastUpdateDate()));
-
- Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> componentsForCatalog = componentCache.getComponentsForCatalog(components, ComponentTypeEnum.RESOURCE);
- if (componentsForCatalog.isLeft()) {
- ImmutablePair<List<Component>, Set<String>> immutablePair = componentsForCatalog.left().value();
- List<Component> foundComponents = immutablePair.getLeft();
- if (foundComponents != null) {
- foundComponents.forEach(p -> result.add((Resource) p));
- log.debug("The number of resources added to catalog from cache is {}", foundComponents.size());
-
- List<String> foundComponentsUid = foundComponents.stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
- notCertifiedHighest = notCertifiedHighest.stream().filter(p -> false == foundComponentsUid.contains(p.getUniqueId())).collect(Collectors.toList());
- }
- Set<String> nonCachedComponents = immutablePair.getRight();
- int numberNonCached = nonCachedComponents == null ? 0 : nonCachedComponents.size();
- log.debug("The number of left resources for catalog is {}", numberNonCached);
-
- }
-
- long endFetchAllFromCache = System.currentTimeMillis();
- log.debug("Fetch all catalog resources metadata from cache took {} ms", (endFetchAllFromCache - startFetchAllFromCache));
-
- long startFetchFromGraph = System.currentTimeMillis();
- log.debug("The number of resources needed to be fetch as light component is {}", notCertifiedHighest.size());
- for (ResourceMetadataData data : notCertifiedHighest) {
- String uniqueId = data.getMetadataDataDefinition().getUniqueId();
- log.trace("Fetch catalog resource non cached {} {}", uniqueId, data.getMetadataDataDefinition().getName());
- Either<Resource, StorageOperationStatus> component = getLightComponent(uniqueId, inTransaction);
- if (component.isRight()) {
- log.debug("Failed to get Service for id = {} error : {} skip resource", data.getUniqueId(), component.right().value());
- } else {
- result.add(component.left().value());
- }
- }
- long endFetchFromGraph = System.currentTimeMillis();
- log.debug("Fetch catalog resources from graph took {} ms", (endFetchFromGraph - startFetchFromGraph));
-
- return Either.left(result);
-
- } finally {
- long end = System.currentTimeMillis();
- log.debug("Fetch all catalog resources took {} ms", end - start);
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- }
- }
-
- public Either<List<Resource>, StorageOperationStatus> getResourceCatalogDataVFLatestCertifiedAndNonCertified(boolean inTransaction) {
- Map<String, Object> propertiesToMatch = new HashMap<>();
- propertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name());
-
- return getResourceCatalogDataLatestCertifiedAndNonCertified(inTransaction, propertiesToMatch);
- }
-
- public Either<List<Resource>, StorageOperationStatus> getResourceCatalogDataLatestCertifiedAndNonCertified(boolean inTransaction, Map<String, Object> otherToMatch) {
- Map<String, Object> propertiesToMatch = new HashMap<>();
-
- if (otherToMatch != null) {
- propertiesToMatch.putAll(otherToMatch);
- }
-
- propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> lastVersionNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class);
-
- List<Resource> result = new ArrayList<>();
-
- if (lastVersionNodes.isRight() && lastVersionNodes.right().value() != TitanOperationStatus.NOT_FOUND) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(lastVersionNodes.right().value()));
- }
-
- List<ResourceMetadataData> listOfHighest;
-
- if (lastVersionNodes.isLeft()) {
- listOfHighest = lastVersionNodes.left().value();
- } else {
- return Either.left(result);
- }
-
- for (ResourceMetadataData data : listOfHighest) {
- Either<Resource, StorageOperationStatus> component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction);
- if (component.isRight()) {
- log.debug("Failed to get Service for id = {} error : {} skip resource", data.getUniqueId(), component.right().value());
- } else {
- result.add(component.left().value());
- }
- }
- return Either.left(result);
- }
-
- private Either<List<Resource>, StorageOperationStatus> getResourceListByCriteria(Map<String, Object> props, boolean inTransaction) {
-
- props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName());
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
-
- if (byCriteria.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value()));
- }
- List<Resource> resources = new ArrayList<>();
- List<ResourceMetadataData> resourcesDataList = byCriteria.left().value();
- for (ResourceMetadataData data : resourcesDataList) {
- buildResource(inTransaction, resources, data);
- }
- return Either.left(resources);
- }
-
- private void buildResource(boolean inTransaction, List<Resource> resources, ResourceMetadataData data) {
- Either<Resource, StorageOperationStatus> resource = getResource(data.getMetadataDataDefinition().getUniqueId(), inTransaction);
- if (resource.isLeft()) {
- resources.add(resource.left().value());
- } else {
- log.debug("Failed to fetch resource for name = {} and id = {}", data.getUniqueId(), data.getMetadataDataDefinition().getName());
- }
- }
-
- public Either<List<Resource>, StorageOperationStatus> getResourceListByUuid(String uuid, boolean inTransaction) {
- return getLatestResourceByUuid(uuid, false, inTransaction);
- }
-
- public Either<List<Resource>, StorageOperationStatus> getLatestResourceByUuid(String uuid, boolean inTransaction) {
- return getLatestResourceByUuid(uuid, true, inTransaction);
- }
-
- private Either<List<Resource>, StorageOperationStatus> getLatestResourceByUuid(String uuid, boolean isLatest, boolean inTransaction) {
- Map<String, Object> props = new HashMap<String, Object>();
- if (isLatest) {
- props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), isLatest);
- }
- props.put(GraphPropertiesDictionary.UUID.getProperty(), uuid);
- return getResourceListByCriteria(props, inTransaction);
- }
-
- public Either<List<Resource>, StorageOperationStatus> getResourceListBySystemName(String systemName, boolean inTransaction) {
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), systemName);
- return getResourceListByCriteria(props, inTransaction);
- }
-
- public Either<List<Resource>, StorageOperationStatus> getResourceListByToscaName(String toscaName, boolean inTransaction) {
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), toscaName);
- return getResourceListByCriteria(props, inTransaction);
- }
-
- public Either<List<Resource>, StorageOperationStatus> getResourceByNameAndVersion(String name, String version, boolean inTransaction) {
- return getByNamesAndVersion(GraphPropertiesDictionary.NAME.getProperty(), name, version, null, inTransaction);
- }
-
- @Override
- public Either<List<Resource>, StorageOperationStatus> getResourceByNameAndVersion(String name, String version) {
- return getResourceByNameAndVersion(name, version, false);
- }
-
- protected Either<List<Resource>, StorageOperationStatus> getByNamesAndVersion(String nameKey, String nameValue, String version, Map<String, Object> additionalParams, boolean inTransaction) {
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(nameKey, nameValue);
- props.put(GraphPropertiesDictionary.VERSION.getProperty(), version);
- props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName());
- if (additionalParams != null && !additionalParams.isEmpty()) {
- props.putAll(additionalParams);
- }
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
- List<Resource> resourcesList = new ArrayList<Resource>();
- if (byCriteria.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value()));
- }
- List<ResourceMetadataData> dataList = byCriteria.left().value();
- if (dataList != null && !dataList.isEmpty()) {
- for (ResourceMetadataData resourceData : dataList) {
- // ResourceMetadataData resourceData = dataList.get(0);
- Either<Resource, StorageOperationStatus> resource = getResource(resourceData.getMetadataDataDefinition().getUniqueId(), inTransaction);
- if (resource.isRight()) {
- log.debug("Failed to fetch resource for name = {} and id = {}", resourceData.getMetadataDataDefinition().getName(), resourceData.getUniqueId());
- return Either.right(resource.right().value());
- }
- resourcesList.add(resource.left().value());
- }
- // return resource;
- return Either.left(resourcesList);
- } else {
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- }
-
- @Override
- protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) getResourceBySystemNameAndVersion(name, version, additionalParams, inTransaction);
- }
-
- @Override
- public Either<Resource, StorageOperationStatus> getResourceBySystemNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction) {
- Either<List<Resource>, StorageOperationStatus> byNamesAndVersion = getByNamesAndVersion(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normaliseComponentName(name), version, additionalParams, inTransaction);
- if (byNamesAndVersion.isRight()) {
- return Either.right(byNamesAndVersion.right().value());
- }
- List<Resource> resourcesList = byNamesAndVersion.left().value();
- if (resourcesList.size() > 1) {
- log.debug("More that one instance of resource for name = {} and version = {}", name, version);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- return Either.left(resourcesList.get(0));
- }
-
- private TitanOperationStatus setAllVersions(Resource resource) {
- Either<Map<String, String>, TitanOperationStatus> res = getVersionList(NodeTypeEnum.Resource, resource.getVersion(), resource, ResourceMetadataData.class);
- if (res.isRight()) {
- return res.right().value();
- }
- resource.setAllVersions(res.left().value());
- return TitanOperationStatus.OK;
- }
-
- @Override
- protected <T extends GraphNode> Either<Map<String, String>, TitanOperationStatus> getVersionList(NodeTypeEnum type, String version, Component component, Class<T> clazz) {
- Map<String, Object> props = new HashMap<String, Object>();
- Map<String, Object> hasNotProps = new HashMap<String, Object>();
-
- if (version.startsWith("0")) {
- props.put(GraphPropertiesDictionary.UUID.getProperty(), component.getUUID());
- } else {
- props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), component.getSystemName());
- props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ((Resource) component).getResourceType().name());
- }
- hasNotProps.put(GraphPropertiesDictionary.IS_DELETED.getProperty(), true);
- Either<List<T>, TitanOperationStatus> result = titanGenericDao.getByCriteria(type, props, hasNotProps, clazz);
-
- Map<String, String> versionMap = new HashMap<String, String>();
- if (result.isRight()) {
- if (!result.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- return Either.right(result.right().value());
- }
-
- } else {
- List<ResourceMetadataData> components = (List<ResourceMetadataData>) result.left().value();
- for (ResourceMetadataData data : components) {
- versionMap.put(data.getMetadataDataDefinition().getVersion(), (String) data.getUniqueId());
- }
- }
-
- return Either.left(versionMap);
- }
-
- /**
- * update only the resource object itself without tag, derived from or any other neighbours.
- *
- * @param resource
- * @param inTransaction
- * @return
- */
- protected Either<Resource, StorageOperationStatus> updateResourceMetadata(Resource resource, boolean inTransaction) {
-
- Either<Resource, StorageOperationStatus> result = null;
-
- try {
-
- log.debug("In updateResource. received resource = {}", (resource == null ? null : resource.toString()));
- if (resource == null) {
- log.error("Resource object is null");
- result = Either.right(StorageOperationStatus.BAD_REQUEST);
- return result;
- }
-
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(resource.getUniqueId());
- resourceData.getMetadataDataDefinition().setHighestVersion(resource.isHighestVersion());
- log.debug("After converting resource to ResourceData. ResourceData = {}", resourceData);
-
- if (resourceData.getUniqueId() == null) {
- log.error("Resource id is missing in the request.");
- return Either.right(StorageOperationStatus.BAD_REQUEST);
- }
-
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(resourceData, ResourceMetadataData.class);
-
- if (updateNode.isRight()) {
- log.error("Failed to update resource {}. status is {}", resource.getUniqueId(), updateNode.right().value());
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()));
- return result;
- }
-
- Either<Resource, StorageOperationStatus> updatedResource = getResource(resource.getUniqueId(), true);
- if (updatedResource.isRight()) {
- log.error("Resource id is missing in the request. status is {}", updatedResource.right().value());
- result = Either.right(StorageOperationStatus.BAD_REQUEST);
- return result;
- }
-
- Resource updatedResourceValue = updatedResource.left().value();
- result = Either.left(updatedResourceValue);
-
- if (log.isDebugEnabled()) {
- String json = prettyJson.toJson(result.left().value());
- log.debug("Resource retrieved after update is {}", json);
- }
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
-
- try {
- List<Resource> result = new ArrayList<>();
- Map<String, Object> propertiesToMatch = new HashMap<>();
- propertiesToMatch.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(), isAbstract);
- propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
-
- if (isHighest != null) {
- propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), isHighest.booleanValue());
- }
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> resourceNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class);
-
- titanGenericDao.commit();
- if (resourceNodes.isRight()) {
- // in case of NOT_FOUND from Titan client return to UI empty
- // list
- if (resourceNodes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- return Either.left(result);
- } else {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceNodes.right().value()));
- }
- } else {
- List<ResourceMetadataData> resourceDataList = resourceNodes.left().value();
- for (ResourceMetadataData resourceData : resourceDataList) {
- Either<Resource, StorageOperationStatus> resource = getResource(resourceData.getMetadataDataDefinition().getUniqueId());
- if (resource.isRight()) {
- log.debug("Failed to fetch resource for id = {} error is {}", resourceData.getUniqueId(), resource.right().value());
- return Either.right(resource.right().value());
- }
- result.add(resource.left().value());
- }
- return Either.left(result);
- }
- } finally {
- titanGenericDao.commit();
- }
-
- }
-
- public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, boolean inTransaction) {
- return getLatestCertifiedByCriteria(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), toscaResourceName, inTransaction);
-
- }
-
- public Either<Resource, StorageOperationStatus> getLatestCertifiedByCriteria(String property, String resourceName, boolean inTransaction) {
- Either<Resource, StorageOperationStatus> result = null;
- try {
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(property, resourceName);
- props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> highestResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
- if (highestResources.isRight()) {
- TitanOperationStatus status = highestResources.right().value();
- log.debug("failed to find resource with name {}. status={} ", resourceName, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- List<ResourceMetadataData> resources = highestResources.left().value();
- double version = 0.0;
- ResourceMetadataData highestResource = null;
- for (ResourceMetadataData resource : resources) {
- double resourceVersion = Double.parseDouble(resource.getMetadataDataDefinition().getVersion());
- if (resourceVersion > version) {
- version = resourceVersion;
- highestResource = resource;
- }
- }
- result = getResource(highestResource.getMetadataDataDefinition().getUniqueId(), true);
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.error("getLatestByName operation : Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("getLatestByName operation : Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
-
- }
- }
-
- public Either<List<Resource>, StorageOperationStatus> findLastCertifiedResourceByName(Resource resource) {
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.NAME.getProperty(), resource.getName());
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
- return getResourceListByCriteria(props, false);
-
- }
-
- public Either<List<Resource>, StorageOperationStatus> findLastCertifiedResourceByUUID(Resource resource) {
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.UUID.getProperty(), resource.getUUID());
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
- return getResourceListByCriteria(props, false);
-
- }
-
- @Override
- public boolean isComponentExist(String resourceId) {
- return isComponentExist(resourceId, NodeTypeEnum.Resource);
- }
-
- @Override
- public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) cloneResource((Resource) other, version, targetLifecycle, inTransaction);
- }
-
- @Override
- public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction) {
- return increaseAndGetComponentInstanceCounter(componentId, NodeTypeEnum.Resource, inTransaction);
- }
-
- private Either<Resource, StorageOperationStatus> cloneResource(Resource other, String version, boolean inTransaction) {
- return cloneResource(other, version, null, inTransaction);
- }
-
- private Either<Resource, StorageOperationStatus> cloneResource(Resource other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) {
- Either<Resource, StorageOperationStatus> result = null;
-
- try {
- String origRsourceId = other.getUniqueId();
-
- StorageOperationStatus overrideStatus = overrideRecursiveMembers(other, origRsourceId);
- if (!overrideStatus.equals(StorageOperationStatus.OK)) {
- return Either.right(overrideStatus);
- }
- other.setVersion(version);
- other.setUniqueId(null);
-
- List<InputDefinition> inputs = other.getInputs();
- Map<String, List<ComponentInstanceProperty>> inputsPropMap = new HashMap<String, List<ComponentInstanceProperty>>();
-
- if(inputs != null){
- for(InputDefinition input: inputs){
-
- Either<List<ComponentInstanceProperty>, TitanOperationStatus> inputPropStatus = inputOperation.getComponentInstancePropertiesByInputId(input.getUniqueId());
- if(inputPropStatus.isLeft()){
- if(inputPropStatus.left().value() != null)
- inputsPropMap.put(input.getName(), inputPropStatus.left().value());
-
- }
-
-
- }
- }
-
- Either<Resource, StorageOperationStatus> createResourceMD = createResource(other, inTransaction);
- if (createResourceMD.isRight()) {
- StorageOperationStatus status = createResourceMD.right().value();
- log.error("failed to clone resource. status= {}", status);
- result = Either.right(status);
- return result;
- }
- Resource resource = createResourceMD.left().value();
- Either<TitanVertex, TitanOperationStatus> metadataVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resource.getUniqueId());
- if (metadataVertexEither.isRight()) {
- TitanOperationStatus error = metadataVertexEither.right().value();
- log.debug("Failed to fetch vertex of metadata {} error {}", resource.getUniqueId(), error);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error));
- return result;
- }
-
- TitanVertex metadataVertex = metadataVertexEither.left().value();
- Either<ImmutablePair<List<ComponentInstance>, Map<String, String>>, StorageOperationStatus> cloneInstances = componentInstanceOperation.cloneAllComponentInstancesFromContainerComponent(origRsourceId, resource.getUniqueId(),
- NodeTypeEnum.Resource, NodeTypeEnum.Resource, targetLifecycle, metadataVertex, other, resource, inputsPropMap);
- if (cloneInstances.isRight()) {
- result = Either.right(cloneInstances.right().value());
- return result;
- }
-
- Either<Integer, StorageOperationStatus> counterStatus = getComponentInstanceCoutner(origRsourceId, NodeTypeEnum.Resource);
- if (counterStatus.isRight()) {
- StorageOperationStatus status = counterStatus.right().value();
- log.error("failed to get resource instance counter on service {}. status={}", origRsourceId, counterStatus);
- result = Either.right(status);
- return result;
- }
-
- Either<Integer, StorageOperationStatus> setResourceInstanceCounter = setComponentInstanceCounter(resource.getUniqueId(), NodeTypeEnum.Resource, counterStatus.left().value(), true);
- if (setResourceInstanceCounter.isRight()) {
- StorageOperationStatus status = setResourceInstanceCounter.right().value();
- log.error("failed to set resource instance counter on service {}. status={}", resource.getUniqueId(), status);
- result = Either.right(status);
- return result;
- }
-
- Either<List<GroupDefinition>, StorageOperationStatus> clonedGroups = cloneGroups(other, resource, cloneInstances.left().value(), true);
- if (clonedGroups.isRight()) {
- StorageOperationStatus status = clonedGroups.right().value();
- if (status != StorageOperationStatus.OK) {
- result = Either.right(status);
- return result;
- }
- }
-
- result = this.getResource(resource.getUniqueId(), true);
- if (result.isRight()) {
- log.error("Cannot get full service from the graph. status is {}", result.right().value());
- return Either.right(result.right().value());
- }
-
- return result;
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- private StorageOperationStatus overrideRecursiveMembers(Resource resource, String prevId) {
- // override requirements to copy only resource's requirements and not
- // derived requirements
- Either<Map<String, List<RequirementDefinition>>, StorageOperationStatus> requirementsOfResourceOnly = getRequirementOperation().getAllRequirementsOfResourceOnly(prevId, true);
- if (requirementsOfResourceOnly.isRight()) {
- log.error("failed to get requirements of resource. resourceId {} status is {}", prevId, requirementsOfResourceOnly.right().value());
- return requirementsOfResourceOnly.right().value();
- }
- resource.setRequirements(requirementsOfResourceOnly.left().value());
-
- // override capabilities to copy only resource's requirements and not
- // derived requirements
- Either<Map<String, List<CapabilityDefinition>>, StorageOperationStatus> capabilitiesOfResourceOnly = getResourceCapabilitiesMap(prevId);
-
- resource.setCapabilities(capabilitiesOfResourceOnly.left().value());
-
- // override interfaces to copy only resource's interfaces and not
- // derived interfaces
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> interfacesOfResourceOnly = getInterfaceLifecycleOperation().getAllInterfacesOfResource(prevId, false, true);
- if (interfacesOfResourceOnly.isRight()) {
- log.error("failed to get interfaces of resource. resourceId {} status is {}", prevId, interfacesOfResourceOnly.right().value());
- return interfacesOfResourceOnly.right().value();
- }
- resource.setInterfaces(interfacesOfResourceOnly.left().value());
-
- List<PropertyDefinition> attributes = new ArrayList<>();
- TitanOperationStatus status = attributeOperation.findNodeNonInheretedAttribues(prevId, NodeTypeEnum.Resource, attributes);
- if (status != TitanOperationStatus.OK) {
- return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- } else {
- resource.setAttributes(attributes);
- }
-
- // override properties to copy only resource's properties and not
- // derived properties
- Either<Map<String, PropertyDefinition>, TitanOperationStatus> propertiesOfResourceOnly = getPropertyOperation().findPropertiesOfNode(NodeTypeEnum.Resource, prevId);
-
- List<PropertyDefinition> resourceProperties = null;
- if (propertiesOfResourceOnly.isRight()) {
- TitanOperationStatus titanStatus = propertiesOfResourceOnly.right().value();
- if (titanStatus != TitanOperationStatus.NOT_FOUND) {
- log.error("failed to get properties of resource. resourceId {} status is {}", prevId, propertiesOfResourceOnly.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus);
- }
- } else {
- Map<String, PropertyDefinition> propertiesMap = propertiesOfResourceOnly.left().value();
- if (propertiesMap != null) {
- resourceProperties = new ArrayList<PropertyDefinition>();
- resourceProperties.addAll(propertiesMap.values());
- }
- }
- resource.setProperties(resourceProperties);
-
- return StorageOperationStatus.OK;
- }
-
- private Either<Map<String, List<CapabilityDefinition>>, StorageOperationStatus> getResourceCapabilitiesMap(String prevId) {
-
- Either<Map<String, CapabilityDefinition>, StorageOperationStatus> capabilitiesOfResourceOnly = getCapabilityOperation().getAllCapabilitiesOfResource(prevId, false, true);
- if (capabilitiesOfResourceOnly.isRight()) {
- log.error("failed to get capabilities of resource. resourceId {} status is {}", prevId, capabilitiesOfResourceOnly.right().value());
- return Either.right(capabilitiesOfResourceOnly.right().value());
- }
- Map<String, List<CapabilityDefinition>> capabilityMap = getCapabilityOperation().convertCapabilityMap(capabilitiesOfResourceOnly.left().value(), null, null);
- return Either.left(capabilityMap);
- }
-
- @Override
- protected StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type) {
- StorageOperationStatus status = StorageOperationStatus.OK;
- List<CategoryDefinition> newCategoryList = component.getCategories();
- CategoryDefinition newCategory = newCategoryList.get(0);
- CategoryDefinition currentCategory = currentComponent.getCategories().get(0);
- boolean categoryWasChanged = false;
-
- if (newCategory.getName() != null && false == newCategory.getName().equals(currentCategory.getName())) {
- // the category was changed
- categoryWasChanged = true;
- } else {
- // the sub-category was changed
- SubCategoryDefinition currSubcategory = currentCategory.getSubcategories().get(0);
- SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0);
- if (newSubcategory.getName() != null && false == newSubcategory.getName().equals(currSubcategory.getName())) {
- log.debug("Going to update the category of the resource from {} to {}", currentCategory, newCategory);
- categoryWasChanged = true;
- }
- }
- if (categoryWasChanged) {
- status = moveCategoryEdge((Resource) component, (ResourceMetadataData) componentData, newCategory);
- log.debug("Going to update the category of the resource from {} to {}. status is {}", currentCategory, newCategory, status);
- }
- return status;
- }
-
- @Override
- public Resource getDefaultComponent() {
- return new Resource();
- }
-
- @Override
- public Either<Component, StorageOperationStatus> getMetadataComponent(String id, boolean inTransaction) {
- return getMetadataComponent(id, NodeTypeEnum.Resource, inTransaction);
- }
-
- @Override
- Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData) {
- return convertResourceDataToResource((ResourceMetadataData) componentMetadataData);
- }
-
- @Override
- public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String componentName) {
- return validateComponentNameUniqueness(componentName, titanGenericDao, NodeTypeEnum.Resource);
- }
-
- @Override
- public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete, boolean inTransaction) {
- return internalMarkComponentToDelete(componentToDelete, inTransaction);
- }
-
- @Override
- public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
- return isResourceInUse(componentId);
- }
-
- @Override
- public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion() {
- return getAllResourcesMarkedForDeletion();
- }
-
- @Override
- public Either<List<String>, StorageOperationStatus> getAllResourcesMarkedForDeletion() {
- return getAllComponentsMarkedForDeletion(NodeTypeEnum.Resource);
- }
-
- @Override
- public Either<Boolean, StorageOperationStatus> isResourceInUse(String resourceToDelete) {
- return isComponentInUse(resourceToDelete, NodeTypeEnum.Resource);
- }
-
- public Either<List<GroupDefinition>, StorageOperationStatus> cloneGroups(Resource resource, Resource newResource, ImmutablePair<List<ComponentInstance>, Map<String, String>> cloneInstances, boolean inTransaction) {
-
- Either<List<GroupDefinition>, StorageOperationStatus> result = null;
-
- if (resource.getGroups() == null) {
- return Either.right(StorageOperationStatus.OK);
- }
-
- Either<List<GroupDefinition>, StorageOperationStatus> prepareGroupsForCloning = groupOperation.prepareGroupsForCloning(resource, cloneInstances);
- if (prepareGroupsForCloning.isRight()) {
- StorageOperationStatus status = prepareGroupsForCloning.right().value();
- if (status != StorageOperationStatus.OK) {
- BeEcompErrorManager.getInstance().logInternalFlowError("CloneResource", "Failed to prepare groups for cloning", ErrorSeverity.ERROR);
- }
- result = Either.right(status);
- return result;
- } else {
- List<GroupDefinition> groupsToCreate = prepareGroupsForCloning.left().value();
- if (groupsToCreate != null && false == groupsToCreate.isEmpty()) {
- Either<List<GroupDefinition>, StorageOperationStatus> addGroups = groupOperation.addGroups(NodeTypeEnum.Resource, newResource.getUniqueId(), groupsToCreate, inTransaction);
- if (addGroups.isRight()) {
- BeEcompErrorManager.getInstance().logInternalFlowError("CloneResource", "Failed to clone groups", ErrorSeverity.ERROR);
- result = Either.right(addGroups.right().value());
- return result;
- }
-
- return Either.left(addGroups.left().value());
- } else {
- return Either.right(StorageOperationStatus.OK);
- }
- }
- }
-
- public Either<Resource, StorageOperationStatus> getLatestResourceByCsarOrName(String csarUUID, String systemName) {
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.CSAR_UUID.getProperty(), csarUUID);
- props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
- ResourceMetadataData resourceMetadataData = null;
- List<ResourceMetadataData> resourceMetadataDataList = null;
- Either<List<ResourceMetadataData>, TitanOperationStatus> byCsar = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
- if (byCsar.isRight()) {
- if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
- //Fix Defect DE256036
- if( StringUtils.isEmpty(systemName)){
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
- }
-
- props.clear();
- props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
- props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), systemName);
- Either<List<ResourceMetadataData>, TitanOperationStatus> bySystemname = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
- if (bySystemname.isRight()) {
- log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
- }
- if (bySystemname.left().value().size() > 2) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- resourceMetadataDataList = bySystemname.left().value();
- if (resourceMetadataDataList.size() == 1) {
- resourceMetadataData = resourceMetadataDataList.get(0);
- } else {
- for (ResourceMetadataData curResource : resourceMetadataDataList) {
- if (!curResource.getMetadataDataDefinition().getState().equals("CERTIFIED")) {
- resourceMetadataData = curResource;
- break;
- }
- }
- }
- if (resourceMetadataData == null) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- if (resourceMetadataData.getMetadataDataDefinition().getCsarUUID() != null && !resourceMetadataData.getMetadataDataDefinition().getCsarUUID().equals(csarUUID)) {
- log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getMetadataDataDefinition().getCsarUUID(), csarUUID);
- // correct error will be returned from create flow. with all
- // correct audit records!!!!!
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- Either<Resource, StorageOperationStatus> resource = getResource((String) resourceMetadataData.getUniqueId());
- return resource;
- }
- } else {
- resourceMetadataDataList = byCsar.left().value();
- if (resourceMetadataDataList.size() > 2) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size());
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- if (resourceMetadataDataList.size() == 1) {
- resourceMetadataData = resourceMetadataDataList.get(0);
- } else {
- for (ResourceMetadataData curResource : resourceMetadataDataList) {
- if (!curResource.getMetadataDataDefinition().getState().equals("CERTIFIED")) {
- resourceMetadataData = curResource;
- break;
- }
- }
- }
- if (resourceMetadataData == null) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- Either<Resource, StorageOperationStatus> resource = getResource((String) resourceMetadataData.getMetadataDataDefinition().getUniqueId());
- return resource;
- }
- return null;
- }
-
- public Either<List<ResourceMetadataData>, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) {
-
- Map<String, Object> props = new HashMap<>();
- props.put(GraphPropertiesDictionary.CSAR_UUID.getProperty(), csarUUID);
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> byCsar = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class);
- if (byCsar.isRight()) {
- if (TitanOperationStatus.NOT_FOUND.equals(byCsar.right().value())) {
- return Either.left(null);
- } else {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCsar.right().value()));
- }
- }
- return Either.left(byCsar.left().value());
- }
-
- public Either<Resource, StorageOperationStatus> getResource(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction) {
-
- Resource resource = null;
- try {
-
- NodeTypeEnum resourceNodeType = NodeTypeEnum.Resource;
- NodeTypeEnum compInstNodeType = NodeTypeEnum.Resource;
-
- Either<ResourceMetadataData, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(uniqueId, resourceNodeType, ResourceMetadataData.class);
- if (componentByLabelAndId.isRight()) {
- return Either.right(componentByLabelAndId.right().value());
- }
- ResourceMetadataData resourceData = componentByLabelAndId.left().value();
-
- // Try to fetch resource from the cache. The resource will be
- // fetched only if the time on the cache equals to
- // the time on the graph.
- Either<Resource, ActionStatus> componentFromCacheIfUpToDate = this.getComponentFromCacheIfUpToDate(uniqueId, resourceData, componentParametersView, Resource.class, ComponentTypeEnum.RESOURCE);
- if (componentFromCacheIfUpToDate.isLeft()) {
- Resource cachedResource = componentFromCacheIfUpToDate.left().value();
- log.debug("Resource {} with uid {} was fetched from cache.", cachedResource.getName(), cachedResource.getUniqueId());
- return Either.left(cachedResource);
- }
-
- resource = convertResourceDataToResource(resourceData);
-
- TitanOperationStatus status = null;
- if (false == componentParametersView.isIgnoreUsers()) {
- status = setResourceCreatorFromGraph(resource, uniqueId);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
-
- status = setResourceLastModifierFromGraph(resource, uniqueId);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
-
- if (false == componentParametersView.isIgnoreProperties()) {
- status = setResourcePropertiesFromGraph(uniqueId, resource);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
-
- if (false == componentParametersView.isIgnoreAttributesFrom()) {
- status = setResourceAttributesFromGraph(uniqueId, resource);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
-
- if (false == componentParametersView.isIgnoreDerivedFrom()) {
- status = setResourceDerivedFromGraph(uniqueId, resource);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
-
- if (false == componentParametersView.isIgnoreCategories()) {
- status = setComponentCategoriesFromGraph(resource);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
-
- // Since capabilities and requirements and instances properties are
- // based on component instances, then we must fetch the instances.
- if (false == componentParametersView.isIgnoreComponentInstances() || false == componentParametersView.isIgnoreComponentInstancesProperties() || false == componentParametersView.isIgnoreComponentInstancesInputs()
- || false == componentParametersView.isIgnoreCapabilities() || false == componentParametersView.isIgnoreRequirements()) {
-
- status = setComponentInstancesFromGraph(uniqueId, resource, resourceNodeType, compInstNodeType);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
-
- }
- }
-
- if (false == componentParametersView.isIgnoreRequirements()) {
- StorageOperationStatus setRequirementsStatus = setResourceRequirementsFromGraph(uniqueId, resource, true);
- if (setRequirementsStatus != StorageOperationStatus.OK) {
- log.error("Failed to set requirement of resource {}. status is {}", uniqueId, setRequirementsStatus);
- return Either.right(setRequirementsStatus);
- }
- }
-
- if (false == componentParametersView.isIgnoreInputs()) {
- status = setComponentInputsFromGraph(uniqueId, resource, true);
- if (status != TitanOperationStatus.OK) {
- log.error("Failed to set inputs of resource {}. status is {}", uniqueId, status);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
-
- }
-
- StorageOperationStatus storageStatus = null;
- if (false == componentParametersView.isIgnoreCapabilities()) {
- storageStatus = setResourceCapabilitiesFromGraph(uniqueId, resource);
- if (storageStatus != StorageOperationStatus.OK) {
- return Either.right(storageStatus);
- }
- }
-
- if (false == componentParametersView.isIgnoreArtifacts()) {
- storageStatus = setArtifactFromGraph(uniqueId, resource);
- if (storageStatus != StorageOperationStatus.OK) {
- return Either.right(storageStatus);
- }
- }
- if (false == componentParametersView.isIgnoreComponentInstancesAttributesFrom()) {
- status = setComponentInstancesAttributesFromGraph(uniqueId, resource);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
-
- }
- }
-
- if (false == componentParametersView.isIgnoreComponentInstancesProperties()) {
- status = setComponentInstancesPropertiesFromGraph(resource);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
-
- }
- }
-
- if (false == componentParametersView.isIgnoreComponentInstancesInputs()) {
- status = setComponentInstancesInputsFromGraph(uniqueId, resource);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
-
- }
- }
-
- if (false == componentParametersView.isIgnoreInterfaces()) {
- storageStatus = setResourceInterfacesFromGraph(uniqueId, resource);
- if (storageStatus != StorageOperationStatus.OK) {
- return Either.right(storageStatus);
- }
- }
-
- if (false == componentParametersView.isIgnoreAdditionalInformation()) {
- storageStatus = setResourceAdditionalInformationFromGraph(uniqueId, resource);
- if (storageStatus != StorageOperationStatus.OK) {
- return Either.right(storageStatus);
- }
- }
-
- if (false == componentParametersView.isIgnoreAllVersions()) {
- status = setAllVersions(resource);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
-
- if (false == componentParametersView.isIgnoreGroups()) {
- status = setGroupsFromGraph(uniqueId, resource, NodeTypeEnum.Resource);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
-
- if (true == componentParametersView.isIgnoreComponentInstances()) {
- resource.setComponentInstances(null);
- resource.setComponentInstancesRelations(null);
- }
-
- } finally {
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- }
-
- return Either.left(resource);
-
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTrasnaction) {
-
- Either<Resource, StorageOperationStatus> component = getResource(id, componentParametersView, inTrasnaction);
- if (component.isRight()) {
- return Either.right(component.right().value());
- }
- return (Either<T, StorageOperationStatus>) component;
- }
-
- // @Override
- public Either<Resource, StorageOperationStatus> updateResource(Resource resource, boolean inTransaction, ComponentParametersView filterResultView) {
- return (Either<Resource, StorageOperationStatus>) updateComponentFilterResult(resource, inTransaction, titanGenericDao, resource.getClass(), NodeTypeEnum.Resource, filterResultView);
- }
-
- @Override
- protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterResultView) {
- return (Either<T, StorageOperationStatus>) updateResource((Resource) component, inTransaction, filterResultView);
- }
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java
deleted file mode 100644
index e503c787b5..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java
+++ /dev/null
@@ -1,1289 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanVertex;
-import fj.data.Either;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
-import org.openecomp.sdc.be.dao.graph.datatype.RelationEndPoint;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.*;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
-import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
-import org.openecomp.sdc.be.resources.data.PropertyData;
-import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
-import org.openecomp.sdc.be.resources.data.UserData;
-import org.openecomp.sdc.be.resources.data.category.CategoryData;
-import org.openecomp.sdc.common.util.ValidationUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.annotation.Resource;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-
-@org.springframework.stereotype.Component("service-operation")
-@Deprecated
-public class ServiceOperation extends ComponentOperation implements IServiceOperation {
-
- private static Logger log = LoggerFactory.getLogger(ServiceOperation.class.getName());
-
- @Resource
- private IArtifactOperation artifactOperation;
-
- @Resource
- private IElementOperation elementOperation;
-
- public ServiceOperation() {
- log.debug("ServiceOperation created");
- }
-
- @Override
- public Either<Service, StorageOperationStatus> createService(Service service) {
- return createService(service, false);
- }
-
- @Override
- public Either<Service, StorageOperationStatus> createService(Service service, boolean inTransaction) {
- Either<Service, StorageOperationStatus> result = null;
-
- try {
-
- ServiceMetadataData serviceData = getServiceMetaDataFromService(service);
- addComponentInternalFields(serviceData);
- String uniqueId = (String) serviceData.getUniqueId();
- generateUUID(service);
-
- String userId = service.getCreatorUserId();
-
- Either<UserData, TitanOperationStatus> findUser = findUser(userId);
-
- if (findUser.isRight()) {
- TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user {} in the graph. status is {}",userId,status);
- return sendError(status, StorageOperationStatus.USER_NOT_FOUND);
- }
-
- UserData creatorUserData = findUser.left().value();
- UserData updaterUserData = creatorUserData;
- String updaterUserId = service.getLastUpdaterUserId();
- if (updaterUserId != null && !updaterUserId.equals(userId)) {
- findUser = findUser(updaterUserId);
- if (findUser.isRight()) {
- TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user {} in the graph. status is {}",userId, status);
- return sendError(status, StorageOperationStatus.USER_NOT_FOUND);
- } else {
- updaterUserData = findUser.left().value();
- }
- }
-
- // get category
- List<CategoryDefinition> categories = service.getCategories();
- CategoryData categoryData = null;
-
- String categoryName = categories.get(0).getName();
- if (categoryName != null) {
- Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ServiceNewCategory, CategoryData.class);
- if (categoryResult.isRight()) {
- StorageOperationStatus status = categoryResult.right().value();
- /*
- * TitanOperationStatus titanStatus = null; if(ActionStatus.CATEGORY_NOT_FOUND.equals(status)){ titanStatus = TitanOperationStatus.NOT_FOUND; }else{ titanStatus = TitanOperationStatus.GENERAL_ERROR; }
- */
- log.error("Cannot find category {} in the graph. status is {}",categoryName,status);
- return Either.right(status);
- }
-
- categoryData = categoryResult.left().value();
- }
-
- StorageOperationStatus storageOperationStatus = createTagsForComponent(service);
- if (storageOperationStatus != StorageOperationStatus.OK) {
- return Either.right(storageOperationStatus);
- }
-
- log.debug("try to create service node on graph for id {}",serviceData.getUniqueId());
- Either<ServiceMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(serviceData, ServiceMetadataData.class);
- if (createNode.isRight()) {
- TitanOperationStatus status = createNode.right().value();
- log.error("Error returned after creating service data node {}. status returned is {}",serviceData,status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- log.debug("create service node created on graph for id {}",serviceData.getUniqueId());
-
- TitanOperationStatus associateMetadata = associateMetadataToComponent(serviceData, creatorUserData, updaterUserData, null, null);
- if (associateMetadata != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateMetadata));
- return result;
- }
- TitanOperationStatus associateCategory = associateMetadataCategoryToComponent(serviceData, categoryData);
- if (associateCategory != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateCategory));
- return result;
- }
-
- Map<String, ArtifactDefinition> allArtifacts = new HashMap<String, ArtifactDefinition>();
- if (service.getArtifacts() != null) {
- allArtifacts.putAll(service.getArtifacts());
- }
- if (service.getDeploymentArtifacts() != null) {
- allArtifacts.putAll(service.getDeploymentArtifacts());
- }
- if (service.getServiceApiArtifacts() != null) {
- allArtifacts.putAll(service.getServiceApiArtifacts());
- }
- if (service.getToscaArtifacts() != null) {
- allArtifacts.putAll(service.getToscaArtifacts());
- }
-
- StorageOperationStatus associateArtifacts = associateArtifactsToComponent(NodeTypeEnum.Service, serviceData, allArtifacts);
- if (associateArtifacts != StorageOperationStatus.OK) {
- result = Either.right(associateArtifacts);
- return result;
- }
-
- TitanOperationStatus associateInputs = associateInputsToComponent(NodeTypeEnum.Service, serviceData, service.getInputs());
- if (associateInputs != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateInputs));
- return result;
- }
-
- List<AdditionalInformationDefinition> additionalInformation = service.getAdditionalInformation();
- StorageOperationStatus addAdditionalInformation = addAdditionalInformationToService(uniqueId, additionalInformation);
- if (addAdditionalInformation != StorageOperationStatus.OK) {
- result = Either.right(addAdditionalInformation);
- return result;
- }
-
- result = this.getService(uniqueId, true);
- if (result.isRight()) {
- log.error("Cannot get full service from the graph. status is {}", result.right().value());
- return Either.right(result.right().value());
- }
-
- if (log.isDebugEnabled()) {
- String json = prettyJson.toJson(result.left().value());
- log.debug("Service retrieved is {}",json);
- }
-
- return result;
-
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- private TitanOperationStatus associateMetadataCategoryToComponent(ServiceMetadataData serviceData, CategoryData categoryData) {
- Either<GraphRelation, TitanOperationStatus> result;
- if (categoryData != null) {
- result = titanGenericDao.createRelation(serviceData, categoryData, GraphEdgeLabels.CATEGORY, null);
- log.debug("After associating component {} to category {}. Edge type is {}",serviceData.getUniqueId(),categoryData,GraphEdgeLabels.CATEGORY);
- if (result.isRight()) {
- log.error("Faield to associate component {} to category {}. Edge type is {}",serviceData.getUniqueId(),categoryData,GraphEdgeLabels.CATEGORY);
- return result.right().value();
- }
- }
- return TitanOperationStatus.OK;
- }
-
- private StorageOperationStatus addAdditionalInformationToService(String resourceUniqueId, List<AdditionalInformationDefinition> additionalInformation) {
-
- StorageOperationStatus result = null;
-
- if (additionalInformation == null || true == additionalInformation.isEmpty()) {
- result = super.addAdditionalInformation(NodeTypeEnum.Service, resourceUniqueId, null);
- } else {
- if (additionalInformation.size() == 1) {
- result = super.addAdditionalInformation(NodeTypeEnum.Service, resourceUniqueId, additionalInformation.get(0));
- } else {
- result = StorageOperationStatus.BAD_REQUEST;
- log.info("Cannot create resource with more than one additional information object. The number of received object is {}", additionalInformation.size());
- }
- }
- return result;
- }
-
- public Either<Service, StorageOperationStatus> cloneService(Service other, String version, boolean inTransaction) {
- return cloneService(other, version, null, inTransaction);
- }
-
- public Either<Service, StorageOperationStatus> cloneService(Service other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) {
- Either<Service, StorageOperationStatus> result = null;
-
- try {
- String origServiceId = other.getUniqueId();
- other.setVersion(version);
- other.setUniqueId(null);
-
- Either<Integer, StorageOperationStatus> counterStatus = getComponentInstanceCoutner(origServiceId, NodeTypeEnum.Service);
- if (counterStatus.isRight()) {
- StorageOperationStatus status = counterStatus.right().value();
- log.error("failed to get resource instance counter on service {}. status={}", origServiceId, counterStatus);
- result = Either.right(status);
- return result;
- }
- Map<String, List<ComponentInstanceInput>> inputsValuesMap = new HashMap<String, List<ComponentInstanceInput>>();
- List<InputDefinition> inputs = other.getInputs();
- if (inputs != null) {
- for (InputDefinition input : inputs) {
-
- Either<List<ComponentInstanceInput>, TitanOperationStatus> inputStatus = inputOperation
- .getComponentInstanceInputsByInputId(input.getUniqueId());
-
- if (inputStatus.isLeft() && inputStatus.left().value() != null) {
- inputsValuesMap.put(input.getName(), inputStatus.left().value());
- }
- }
- }
-
- Either<Service, StorageOperationStatus> createServiceMD = createService(other, true);
-
- if (createServiceMD.isRight()) {
- StorageOperationStatus status = createServiceMD.right().value();
- log.error("failed to clone service. status= {}", status);
- result = Either.right(status);
- return result;
- }
-
- Service service = createServiceMD.left().value();
-
- Either<ImmutablePair<List<ComponentInstance>, Map<String, String>>, StorageOperationStatus> cloneInstances = componentInstanceOperation.cloneAllComponentInstancesFromContainerComponent(origServiceId, service,
- NodeTypeEnum.Service, NodeTypeEnum.Resource, targetLifecycle, inputsValuesMap);
- if (cloneInstances.isRight()) {
- result = Either.right(cloneInstances.right().value());
- return result;
- }
-
- Either<Integer, StorageOperationStatus> setResourceInstanceCounter = setComponentInstanceCounter(service.getUniqueId(), NodeTypeEnum.Service, counterStatus.left().value(), true);
- if (setResourceInstanceCounter.isRight()) {
- StorageOperationStatus status = setResourceInstanceCounter.right().value();
- log.error("failed to set resource instance counter on service {}. status={}", service.getUniqueId(), setResourceInstanceCounter);
- result = Either.right(status);
- return result;
- }
-
- result = this.getService(service.getUniqueId(), true);
- if (result.isRight()) {
- log.error("Cannot get full service from the graph. status is {}", result.right().value());
- return Either.right(result.right().value());
- }
-
- if (log.isTraceEnabled()) {
- String json = prettyJson.toJson(result.left().value());
- log.trace("Resource retrieved is {}", json);
- }
-
- return result;
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
- }
-
- private ServiceMetadataData getServiceMetaDataFromService(Service service) {
- ServiceMetadataData serviceData = new ServiceMetadataData((ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition());
- if (service.getNormalizedName() == null || service.getNormalizedName().isEmpty()) {
- serviceData.getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(service.getName()));
- }
- if (service.getSystemName() == null || service.getSystemName().isEmpty()) {
- serviceData.getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(service.getName()));
- }
-
- return serviceData;
- }
-
- private Either<Service, StorageOperationStatus> sendError(TitanOperationStatus status, StorageOperationStatus statusIfNotFound) {
- Either<Service, StorageOperationStatus> result;
- if (status == TitanOperationStatus.NOT_FOUND) {
- result = Either.right(statusIfNotFound);
- return result;
- } else {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- }
-
- /**
- *
- */
- public Either<Service, StorageOperationStatus> getService(String uniqueId) {
- return getService(uniqueId, false);
- }
-
- public Either<Service, StorageOperationStatus> getService(String uniqueId, boolean inTransaction) {
- ComponentParametersView componentParametersView = new ComponentParametersView();
- return getService(uniqueId, componentParametersView, inTransaction);
- }
-
- public Either<Service, StorageOperationStatus> getService(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction) {
-
- Service service = null;
- Either<Service, StorageOperationStatus> result = null;
- try {
-
- NodeTypeEnum serviceNodeType = NodeTypeEnum.Service;
- NodeTypeEnum compInstNodeType = NodeTypeEnum.Resource;
-
- Either<ServiceMetadataData, StorageOperationStatus> getComponentByLabel = getComponentByLabelAndId(uniqueId, serviceNodeType, ServiceMetadataData.class);
- if (getComponentByLabel.isRight()) {
- result = Either.right(getComponentByLabel.right().value());
- return result;
- }
- ServiceMetadataData serviceData = getComponentByLabel.left().value();
- // Try to fetch resource from the cache. The resource will be
- // fetched only if the time on the cache equals to
- // the time on the graph.
- Either<Service, ActionStatus> componentFromCacheIfUpToDate = this.getComponentFromCacheIfUpToDate(uniqueId, serviceData, componentParametersView, Service.class, ComponentTypeEnum.SERVICE);
- if (componentFromCacheIfUpToDate.isLeft()) {
- Service cachedService = componentFromCacheIfUpToDate.left().value();
- log.debug("Service {} with uid {} was fetched from cache.", cachedService.getName(), cachedService.getUniqueId());
- return Either.left(cachedService);
- }
-
- service = convertServiceDataToService(serviceData);
- TitanOperationStatus status = null;
- if (false == componentParametersView.isIgnoreUsers()) {
- status = setComponentCreatorFromGraph(service, uniqueId, serviceNodeType);
- if (status != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- status = setComponentLastModifierFromGraph(service, uniqueId, serviceNodeType);
- if (status != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
-
- }
- }
- if (false == componentParametersView.isIgnoreCategories()) {
- status = setComponentCategoriesFromGraph(service);
- if (status != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
-
- }
- }
-
- if (false == componentParametersView.isIgnoreArtifacts()) {
- StorageOperationStatus storageStatus = setArtifactFromGraph(uniqueId, service, serviceNodeType, artifactOperation);
- if (storageStatus != StorageOperationStatus.OK) {
- result = Either.right(storageStatus);
- return result;
- }
- }
-
- if (false == componentParametersView.isIgnoreComponentInstances() || false == componentParametersView.isIgnoreComponentInstancesProperties() || false == componentParametersView.isIgnoreCapabilities()
- || false == componentParametersView.isIgnoreRequirements()) {
- status = setComponentInstancesFromGraph(uniqueId, service, serviceNodeType, compInstNodeType);
- if (status != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
-
- }
- }
- if (false == componentParametersView.isIgnoreComponentInstancesProperties()) {
- status = setComponentInstancesPropertiesFromGraph(service);
- if (status != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- }
- if (false == componentParametersView.isIgnoreCapabilities()) {
- status = setCapabilitiesFromGraph(uniqueId, service, NodeTypeEnum.Service);
- if (status != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- }
- if (false == componentParametersView.isIgnoreRequirements()) {
- status = setRequirementsFromGraph(uniqueId, service, NodeTypeEnum.Service);
- if (status != TitanOperationStatus.OK) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- }
- if (false == componentParametersView.isIgnoreAllVersions()) {
- status = setAllVersions(service);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
- if (false == componentParametersView.isIgnoreAdditionalInformation()) {
- status = setServiceAdditionalInformationFromGraph(uniqueId, service);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
-
- if (false == componentParametersView.isIgnoreGroups()) {
- status = setGroupsFromGraph(uniqueId, service, NodeTypeEnum.Resource);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- }
- if (false == componentParametersView.isIgnoreInputs()) {
- status = setComponentInputsFromGraph(uniqueId, service, true);
- if (status != TitanOperationStatus.OK) {
- log.error("Failed to set inputs of resource {}. status is {}",uniqueId,status);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
-
- }
-
- if (false == componentParametersView.isIgnoreComponentInstancesInputs()) {
- status = setComponentInstancesInputsFromGraph(uniqueId, service);
- if (status != TitanOperationStatus.OK) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
-
- }
- }
-
- result = Either.left(service);
- return result;
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- titanGenericDao.rollback();
- } else {
- titanGenericDao.commit();
- }
- }
- }
- }
-
- // public Either<Service, StorageOperationStatus> getService_tx(String
- // uniqueId, boolean inTransaction) {
- //
- // Service service = null;
- // Either<Service, StorageOperationStatus> result = null;
- // try {
- //
- // NodeTypeEnum serviceNodeType = NodeTypeEnum.Service;
- // NodeTypeEnum compInstNodeType = NodeTypeEnum.Resource;
- //
- // Either<ServiceMetadataData, StorageOperationStatus> getComponentByLabel =
- // getComponentByLabelAndId_tx(uniqueId, serviceNodeType,
- // ServiceMetadataData.class);
- // if (getComponentByLabel.isRight()) {
- // result = Either.right(getComponentByLabel.right().value());
- // return result;
- // }
- // ServiceMetadataData serviceData = getComponentByLabel.left().value();
- // service = convertServiceDataToService(serviceData);
- //
- // TitanOperationStatus status = setComponentCreatorFromGraph(service,
- // uniqueId, serviceNodeType);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- // }
- //
- // status = setComponentLastModifierFromGraph(service, uniqueId,
- // serviceNodeType);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- //
- // }
- // status = setComponentCategoriesFromGraph(service);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- //
- // }
- //
- // // status = setServicePropertiesFromGraph(uniqueId, resource, vertex);
- // // if (status != TitanOperationStatus.OK) {
- // // return
- // Either.right(TitanStatusConverter.convertTitanStatusToStorageStatus(status));
- // // }
- //
- // StorageOperationStatus storageStatus = setArtifactFromGraph(uniqueId,
- // service, serviceNodeType, artifactOperation);
- // if (storageStatus != StorageOperationStatus.OK) {
- // result = Either.right(storageStatus);
- // return result;
- // }
- //
- // status = setComponentInstancesFromGraph(uniqueId, service,
- // serviceNodeType, compInstNodeType);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- //
- // }
- //
- // status = setComponentInstancesPropertiesFromGraph(uniqueId, service);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- // }
- //
- // status = setCapabilitiesFromGraph(uniqueId, service,
- // NodeTypeEnum.Service);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- // }
- //
- // status = setRequirementsFromGraph( uniqueId, service,
- // NodeTypeEnum.Service);
- // if (status != TitanOperationStatus.OK) {
- // result =
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // return result;
- // }
- //
- // status = setAllVersions(service);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // status = setServiceAdditionalInformationFromGraph(uniqueId, service);
- // if (status != TitanOperationStatus.OK) {
- // return
- // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- // }
- //
- // result = Either.left(service);
- // return result;
- // } finally {
- // if (false == inTransaction) {
- // if (result == null || result.isRight()) {
- // titanGenericDao.rollback();
- // } else {
- // titanGenericDao.commit();
- // }
- // }
- // }
- // }
-
- @Override
- TitanOperationStatus setComponentCategoriesFromGraph(Component service) {
-
- String uniqueId = service.getUniqueId();
- Either<List<ImmutablePair<CategoryData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId, GraphEdgeLabels.CATEGORY,
- NodeTypeEnum.ServiceNewCategory, CategoryData.class);
- if (parentNode.isRight()) {
- return parentNode.right().value();
- }
-
- List<ImmutablePair<CategoryData, GraphEdge>> listValue = parentNode.left().value();
- if (log.isDebugEnabled())
- log.debug("Result after looking for category nodes pointed by service {}. status is {}", uniqueId, listValue);
- if (listValue.size() > 1) {
- log.error("Multiple edges foud between resource {} to category nodes.",uniqueId);
- }
- ImmutablePair<CategoryData, GraphEdge> value = listValue.get(0);
- if (log.isDebugEnabled())
- log.debug("Found parent node {}", value);
-
- CategoryData categoryData = value.getKey();
- CategoryDefinition categoryDefinition = new CategoryDefinition(categoryData.getCategoryDataDefinition());
-
- List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(categoryDefinition);
- service.setCategories(categories);
- return TitanOperationStatus.OK;
-
- }
-
- @Override
- public Either<Service, StorageOperationStatus> deleteService(String serviceId) {
- return deleteService(serviceId, false);
- }
-
- @Override
- public Either<Service, StorageOperationStatus> deleteService(String serviceId, boolean inTransaction) {
-
- Either<Service, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR);
- try {
-
- Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
- if (graphResult.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value()));
- return result;
- }
-
- Either<ServiceMetadataData, TitanOperationStatus> serviceNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), serviceId, ServiceMetadataData.class);
- if (serviceNode.isRight()) {
- TitanOperationStatus status = serviceNode.right().value();
- log.error("Failed to find service {}. status is {}",serviceId,status);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
-
- Either<Service, StorageOperationStatus> serviceRes = getService(serviceId, true);
- if (serviceRes.isRight()) {
- StorageOperationStatus status = serviceRes.right().value();
- log.error("Failed to find sevice {}.status is {}",serviceId,status);
- result = Either.right(status);
- return result;
- }
- Service service = serviceRes.left().value();
-
- Either<List<ComponentInstance>, StorageOperationStatus> deleteAllResourceInstancesRes = componentInstanceOperation.deleteAllComponentInstances(serviceId, NodeTypeEnum.Service, true);
- log.debug("After deleting resource instances under service {}.Result is {}",serviceId,deleteAllResourceInstancesRes);
- if (deleteAllResourceInstancesRes.isRight()) {
- StorageOperationStatus status = deleteAllResourceInstancesRes.right().value();
- if (status != StorageOperationStatus.NOT_FOUND) {
- log.error("Failed to delete resource instances under service {} .status is ",serviceId,status);
- result = Either.right(status);
- return result;
- }
- }
- StorageOperationStatus removeArtifactsFromResource = removeArtifactsFromComponent(service, NodeTypeEnum.Service);
- log.debug("After deleting artifacts nodes in the graph. status is {}",removeArtifactsFromResource);
- if (!removeArtifactsFromResource.equals(StorageOperationStatus.OK)) {
- result = Either.right(removeArtifactsFromResource);
- return result;
- }
-
- StorageOperationStatus removeInputsFromResource = removeInputsFromComponent(NodeTypeEnum.Service, service);
- log.debug("After deleting requirements nodes in the graph. status is {}",removeInputsFromResource);
- if (removeInputsFromResource != StorageOperationStatus.OK) {
- result = Either.right(removeInputsFromResource);
- return result;
- }
-
- Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deleteChildrenNodesRes = titanGenericDao.deleteChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), serviceId, GraphEdgeLabels.PROPERTY,
- NodeTypeEnum.Property, PropertyData.class);
-
- if (deleteChildrenNodesRes.isRight()) {
- TitanOperationStatus status = deleteChildrenNodesRes.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- }
-
- StorageOperationStatus removeAdditionalInformationFromService = super.deleteAdditionalInformation(NodeTypeEnum.Service, serviceId);
- log.debug("After deleting additional information node in the graph. status is {}",removeAdditionalInformationFromService);
- if (!removeAdditionalInformationFromService.equals(StorageOperationStatus.OK)) {
- result = Either.right(removeAdditionalInformationFromService);
- return result;
- }
-
- StorageOperationStatus removeGroupsFromService = super.deleteGroups(NodeTypeEnum.Service, serviceId);
- log.debug("After deleting group nodes in the graph. status is {}",removeGroupsFromService);
- if (!removeGroupsFromService.equals(StorageOperationStatus.OK)) {
- result = Either.right(removeGroupsFromService);
- return result;
- }
-
- Either<ServiceMetadataData, TitanOperationStatus> deleteServiceNodeRes = titanGenericDao.deleteNode(serviceNode.left().value(), ServiceMetadataData.class);
- if (deleteServiceNodeRes.isRight()) {
- TitanOperationStatus status = deleteServiceNodeRes.right().value();
- log.error("Failed to delete service node {}. status is {}",serviceId, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- result = Either.left(service);
-
- return result;
- } finally {
- if (false == inTransaction) {
- if (result == null || result.isRight()) {
- log.debug("deleteService operation : Going to execute rollback on graph.");
- titanGenericDao.rollback();
- } else {
- log.debug("deleteService operation : Going to execute commit on graph.");
- titanGenericDao.commit();
- }
- }
- }
-
- }
-
- @Override
- public Either<Boolean, StorageOperationStatus> validateServiceNameExists(String serviceName) {
- return validateServiceNameUniqueness(serviceName, titanGenericDao);
- }
-
- private Service convertServiceDataToService(ServiceMetadataData serviceData) {
- ServiceMetadataDefinition serviceMetadataDefinition = new ServiceMetadataDefinition((ServiceMetadataDataDefinition) serviceData.getMetadataDataDefinition());
-
- Service service = new Service(serviceMetadataDefinition);
-
- return service;
- }
-
- @Override
- public <T extends Component> Either<T, StorageOperationStatus> getComponent(String id, Class<T> clazz) {
-
- Either<Service, StorageOperationStatus> component = getService(id);
- if (component.isRight()) {
- return Either.right(component.right().value());
- }
- return Either.left(clazz.cast(component.left().value()));
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public Either<List<Service>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction) {
-
- return (Either<List<Service>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getFollowedComponent(userId, lifecycleStates, lastStateStates, inTransaction, titanGenericDao, NodeTypeEnum.Service);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> Either<T, StorageOperationStatus> getComponent(String id, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) getService(id, inTransaction);
- }
-
- @Override
- public Either<Set<Service>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch, boolean inTransaction) {
- return getComponentCatalogData(NodeTypeEnum.Service, propertiesToMatch, Service.class, ServiceMetadataData.class, inTransaction);
- }
-
- @Override
- public Either<Service, StorageOperationStatus> updateService(Service service, boolean inTransaction) {
- Either<Service, StorageOperationStatus> result = updateComponent(service, inTransaction, titanGenericDao, Service.class, NodeTypeEnum.Service);
- return result;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> Either<T, StorageOperationStatus> updateComponent(T component, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) updateService((Service) component, inTransaction);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Either<Component, StorageOperationStatus> deleteComponent(String id, boolean inTransaction) {
- return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteService(id, inTransaction);
- }
-
- @Override
- protected ComponentMetadataData getMetaDataFromComponent(Component component) {
- return getServiceMetaDataFromService((Service) component);
- }
-
- @Override
- public <T> Either<T, StorageOperationStatus> getLightComponent(String id, boolean inTransaction) {
- return getLightComponent(id, NodeTypeEnum.Service, inTransaction);
- }
-
- @Override
- public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
- Either<List<T>, StorageOperationStatus> components = null;
-
- String categoryName = filters.get(FilterKeyEnum.CATEGORY);
- String distributionStatus = filters.get(FilterKeyEnum.DISTRIBUTION_STATUS);
- DistributionStatusEnum distEnum = DistributionStatusEnum.findState(distributionStatus);
- if (distributionStatus != null && distEnum == null) {
- filters.remove(FilterKeyEnum.CATEGORY);
- return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND);
- }
-
- if (categoryName != null) { // primary filter
- components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), NodeTypeEnum.Service, inTransaction, ServiceMetadataData.class, null);
- if (components.isLeft() && distEnum != null) {// secondary filter
- Predicate<T> statusFilter = p -> ((Service) p).getDistributionStatus().equals(distEnum);
- return Either.left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList()));
- }
- filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS);
- return components;
- }
- components = fetchByDistributionStatus(distEnum.name(), inTransaction);
- if (components.isRight()) { // not found == empty list
- return Either.left(new ArrayList<>());
- }
- return components;
- }
-
- private <T> Either<List<T>, StorageOperationStatus> fetchByDistributionStatus(String status, boolean inTransaction) {
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.DISTRIBUTION_STATUS.getProperty(), status);
- props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
- return (Either<List<T>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getServiceListByCriteria(props, inTransaction);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Either<List<Service>, StorageOperationStatus> getTesterFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction) {
- return (Either<List<Service>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getTesterFollowedComponent(userId, lifecycleStates, inTransaction, NodeTypeEnum.Service);
- }
-
- @Override
- public Either<Service, StorageOperationStatus> updateDestributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
- String userId = user.getUserId();
- Either<UserData, TitanOperationStatus> findUser = findUser(userId);
- if (findUser.isRight()) {
- TitanOperationStatus status = findUser.right().value();
- log.error("Cannot find user {} in the graph. status is {}", userId, status);
- return sendError(status, StorageOperationStatus.USER_NOT_FOUND);
- }
- UserData userData = findUser.left().value();
-
- Either<ServiceMetadataData, TitanOperationStatus> serviceMetadataDataRequeset = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), service.getUniqueId(), ServiceMetadataData.class);
- if (serviceMetadataDataRequeset.isRight()) {
- TitanOperationStatus status = serviceMetadataDataRequeset.right().value();
- log.error("Cannot find service {} in the graph. status is {}",service.getUniqueId(),status);
- return sendError(status, StorageOperationStatus.NOT_FOUND);
- }
- ServiceMetadataData serviceMetadataData = serviceMetadataDataRequeset.left().value();
-
- StorageOperationStatus result = StorageOperationStatus.OK;
-
- Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = deleteLastDistributionModifierRelation(service);
- if (deleteIncomingRelation.isRight() && deleteIncomingRelation.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.error("Failed to delete user from component {}. Edge type is {}",service.getUniqueId(),GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER);
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteIncomingRelation.right().value());
- return Either.right(result);
- }
-
- Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(userData, serviceMetadataData, GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER, null);
- log.debug("After associating user {} to component {}. Edge type is {}",userData,serviceMetadataData.getUniqueId(),GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER);
- if (createRelation.isRight()) {
- log.error("Failed to associate user {} to component {}. Edge type is {}",userData,serviceMetadataData.getUniqueId(),GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER);
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value());
- return Either.right(result);
- }
- service.setDistributionStatus(distributionStatus);
- Either<Service, StorageOperationStatus> updateResponse = updateComponent(service, true, titanGenericDao, Service.class, NodeTypeEnum.Service);
-
- return updateResponse;
-
- }
-
- private Either<GraphRelation, TitanOperationStatus> deleteLastDistributionModifierRelation(Service service) {
- GraphRelation lastDistributionStateModifaierRelation = new GraphRelation();
- lastDistributionStateModifaierRelation.setType(GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER.getProperty());
- RelationEndPoint relationEndPoint = new RelationEndPoint(NodeTypeEnum.Service, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), service.getUniqueId());
- lastDistributionStateModifaierRelation.setTo(relationEndPoint);
- Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = titanGenericDao.deleteIncomingRelation(lastDistributionStateModifaierRelation);
- return deleteIncomingRelation;
- }
-
- @Override
- public Either<Set<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Map<String, Object> propertiesToMatch, Set<DistributionStatusEnum> distStatus, boolean inTransaction) {
- log.debug("Start getCertifiedServicesWithDistStatus.");
- Set<Service> servicesSet = new HashSet<Service>();
- if (distStatus != null && !distStatus.isEmpty()) {
- for (DistributionStatusEnum status : distStatus) {
- Map<String, Object> props = new HashMap<>();
- props.putAll(propertiesToMatch);
- props.put(GraphPropertiesDictionary.DISTRIBUTION_STATUS.getProperty(), status.name());
- Either<Set<Service>, StorageOperationStatus> services = retrieveCertifiedServicesWithStatus(inTransaction, props);
- if (services.isRight()) {
- return services;
- } else {
- servicesSet.addAll(services.left().value());
- }
- }
- return Either.left(servicesSet);
- } else {
- return retrieveCertifiedServicesWithStatus(inTransaction, propertiesToMatch);
- }
- }
-
- private Either<Set<Service>, StorageOperationStatus> retrieveCertifiedServicesWithStatus(boolean inTransaction, Map<String, Object> props) {
- Either<List<ServiceMetadataData>, TitanOperationStatus> criteriaRes = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class);
- return retrieveComponentsFromNodes(criteriaRes, inTransaction);
- }
-
- public Either<List<Service>, StorageOperationStatus> getServiceCatalogData(boolean inTransaction) {
-
- long start = System.currentTimeMillis();
-
- try {
- /*
- * Map<String, Object> propertiesToMatch = new HashMap<>(); propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty (), LifecycleStateEnum.CERTIFIED.name()); Either<List<ServiceMetadataData>, TitanOperationStatus>
- * lastVersionNodes = getLastVersion(NodeTypeEnum.Service, propertiesToMatch, ServiceMetadataData.class); if (lastVersionNodes.isRight() && lastVersionNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return
- * Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus (lastVersionNodes.right().value())); } List<ServiceMetadataData> notCertifiedHighest = (lastVersionNodes.isLeft() ? lastVersionNodes.left().value() : new
- * ArrayList<ServiceMetadataData>());
- *
- * propertiesToMatch.put(GraphPropertiesDictionary. IS_HIGHEST_VERSION.getProperty(), true); Either<List<ServiceMetadataData>, TitanOperationStatus> componentsNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Service, propertiesToMatch,
- * ServiceMetadataData.class); if (componentsNodes.isRight() && componentsNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus
- * (componentsNodes.right().value())); } List<ServiceMetadataData> certifiedHighest = (componentsNodes.isLeft() ? componentsNodes.left().value() : new ArrayList<ServiceMetadataData>());
- */
-
- Either<List<ServiceMetadataData>, TitanOperationStatus> listOfHighestComponents = this.getListOfHighestComponents(NodeTypeEnum.Service, ServiceMetadataData.class);
- if (listOfHighestComponents.isRight() && listOfHighestComponents.right().value() != TitanOperationStatus.NOT_FOUND) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestComponents.right().value()));
- }
-
- List<ServiceMetadataData> notCertifiedHighest = listOfHighestComponents.left().value();
-
- List<Service> result = new ArrayList<>();
-
- if (notCertifiedHighest != null && false == notCertifiedHighest.isEmpty()) {
-
- // fetch from cache
- long startFetchAllFromCache = System.currentTimeMillis();
-
- Map<String, Long> components = notCertifiedHighest.stream().collect(Collectors.toMap(p -> p.getMetadataDataDefinition().getUniqueId(), p -> p.getMetadataDataDefinition().getLastUpdateDate()));
-
- Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> componentsFromCacheForCatalog = this.getComponentsFromCacheForCatalog(components, ComponentTypeEnum.SERVICE);
- if (componentsFromCacheForCatalog.isLeft()) {
- ImmutablePair<List<Component>, Set<String>> immutablePair = componentsFromCacheForCatalog.left().value();
- List<Component> list = immutablePair.getLeft();
- if (list != null) {
- for (Component component : list) {
- result.add((Service) component);
- }
- List<String> addedUids = list.stream().map(p -> p.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId()).collect(Collectors.toList());
- notCertifiedHighest = notCertifiedHighest.stream().filter(p -> false == addedUids.contains(p.getMetadataDataDefinition().getUniqueId())).collect(Collectors.toList());
- }
- }
- long endFetchAllFromCache = System.currentTimeMillis();
- log.debug("Fetch all catalog services metadata from cache took {} ms", (endFetchAllFromCache - startFetchAllFromCache));
- log.debug("The number of services added to catalog from cache is {}", result.size());
-
- log.debug("The number of services needed to be fetch as light component is {}", notCertifiedHighest.size());
- for (ServiceMetadataData data : notCertifiedHighest) {
- Either<Service, StorageOperationStatus> component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction);
- if (component.isRight()) {
- log.debug("Failed to get Service for id = {}, error : {}. Skip service", data.getUniqueId(), component.right().value());
- } else {
- result.add(component.left().value());
- }
- }
- }
- return Either.left(result);
- } finally {
- if (false == inTransaction) {
- titanGenericDao.commit();
- }
- log.debug("Fetch all catalog services took {} ms",(System.currentTimeMillis() - start));
- }
-
- }
-
- public Either<List<Service>, StorageOperationStatus> getServiceCatalogDataLatestCertifiedAndNotCertified(boolean inTransaction) {
- Map<String, Object> properties = new HashMap<>();
-
- properties.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
- List<Service> result = new ArrayList<>();
- Either<List<ServiceMetadataData>, TitanOperationStatus> lastVersionNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Service, properties, ServiceMetadataData.class);
-
- if (lastVersionNodes.isRight() && lastVersionNodes.right().value() != TitanOperationStatus.NOT_FOUND) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(lastVersionNodes.right().value()));
- }
-
- List<ServiceMetadataData> latestServices;
-
- if (lastVersionNodes.isLeft()) {
- latestServices = lastVersionNodes.left().value();
- } else {
- return Either.left(result);
- }
-
- for (ServiceMetadataData data : latestServices) {
- Either<Service, StorageOperationStatus> component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction);
- if (component.isRight()) {
- log.debug("Failed to get Service for id = {} error : {} skip resource",data.getUniqueId(),component.right().value());
- } else {
- result.add(component.left().value());
- }
- }
-
- return Either.left(result);
-
- }
-
- private Either<List<Service>, StorageOperationStatus> getServiceListByCriteria(Map<String, Object> props, boolean inTransaction) {
- props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName());
- Either<List<ServiceMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class);
-
- if (byCriteria.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value()));
- }
- List<Service> services = new ArrayList<>();
- List<ServiceMetadataData> servicesDataList = byCriteria.left().value();
- for (ServiceMetadataData data : servicesDataList) {
- Either<Service, StorageOperationStatus> service = getService(data.getMetadataDataDefinition().getUniqueId(), inTransaction);
- if (service.isLeft()) {
- services.add(service.left().value());
- } else {
- log.debug("Failed to fetch resource for name = {} and id = {}",data.getMetadataDataDefinition().getName(),data.getUniqueId());
- }
- }
- return Either.left(services);
- }
-
- public Either<List<Service>, StorageOperationStatus> getServiceListByUuid(String uuid, boolean inTransaction) {
- return getLatestServiceByUuid(uuid, false, inTransaction);
- }
-
- public Either<List<Service>, StorageOperationStatus> getLatestServiceByUuid(String uuid, boolean inTransaction) {
- return getLatestServiceByUuid(uuid, true, inTransaction);
- }
-
- private Either<List<Service>, StorageOperationStatus> getLatestServiceByUuid(String uuid, boolean isLatest, boolean inTransaction) {
- Map<String, Object> props = new HashMap<String, Object>();
-
- if (isLatest) {
- props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), isLatest);
- }
-
- props.put(GraphPropertiesDictionary.UUID.getProperty(), uuid);
- return getServiceListByCriteria(props, inTransaction);
- }
-
- @Override
- public Either<List<Service>, StorageOperationStatus> getAll() {
- Either<List<Service>, StorageOperationStatus> serviceListByCriteria = getServiceListByCriteria(new HashMap<>(), false);
- if (serviceListByCriteria.isRight() && serviceListByCriteria.right().value() == StorageOperationStatus.NOT_FOUND) {
- return Either.left(Collections.emptyList());
- }
- return serviceListByCriteria;
- }
-
- public Either<List<Service>, StorageOperationStatus> getServiceListBySystemName(String systemName, boolean inTransaction) {
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), systemName);
- return getServiceListByCriteria(props, inTransaction);
- }
-
- public Either<Service, StorageOperationStatus> getServiceByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction) {
- return getByNamesAndVersion(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normaliseComponentName(name), version, additionalParams, inTransaction);
- }
-
- @Override
- public Either<Service, StorageOperationStatus> getServiceByNameAndVersion(String name, String version) {
- return getServiceByNameAndVersion(name, version, null, false);
- }
-
- protected Either<Service, StorageOperationStatus> getByNamesAndVersion(String nameKey, String nameValue, String version, Map<String, Object> additionalParams, boolean inTransaction) {
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(nameKey, nameValue);
- props.put(GraphPropertiesDictionary.VERSION.getProperty(), version);
- props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName());
- if (additionalParams != null && !additionalParams.isEmpty()) {
- props.putAll(additionalParams);
- }
-
- Either<List<ServiceMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class);
-
- if (byCriteria.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value()));
- }
- List<ServiceMetadataData> dataList = byCriteria.left().value();
- if (dataList != null && !dataList.isEmpty()) {
- if (dataList.size() > 1) {
- log.debug("More that one instance of resource for name ={} and version = {}",nameValue,version);
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- ServiceMetadataData serviceData = dataList.get(0);
- Either<Service, StorageOperationStatus> service = getService(serviceData.getMetadataDataDefinition().getUniqueId(), inTransaction);
- if (service.isRight()) {
- log.debug("Failed to fetch resource for name = {} and id = {}",serviceData.getMetadataDataDefinition().getName(),serviceData.getMetadataDataDefinition().getUniqueId());
- }
- return service;
- }
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
-
- protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) getServiceByNameAndVersion(name, version, additionalParams, inTransaction);
- }
-
- @Override
- public Either<Service, StorageOperationStatus> getServiceBySystemNameAndVersion(String name, String version, boolean inTransaction) {
- return getByNamesAndVersion(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), name, version, null, inTransaction);
- }
-
- private TitanOperationStatus setServiceAdditionalInformationFromGraph(String uniqueId, Service service) {
-
- List<AdditionalInformationDefinition> additionalInformation = new ArrayList<>();
-
- Either<AdditionalInformationDefinition, TitanOperationStatus> either = additionalInformationOperation.getAllAdditionalInformationParameters(NodeTypeEnum.Service, uniqueId, true);
-
- if (either.isRight()) {
- TitanOperationStatus status = either.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- return TitanOperationStatus.OK;
- }
- return status;
- }
-
- AdditionalInformationDefinition additionalInformationDefinition = either.left().value();
- additionalInformation.add(additionalInformationDefinition);
-
- service.setAdditionalInformation(additionalInformation);
-
- return TitanOperationStatus.OK;
-
- }
-
- private TitanOperationStatus setAllVersions(Service service) {
- Either<Map<String, String>, TitanOperationStatus> res = getVersionList(NodeTypeEnum.Service, service.getVersion(), service, ServiceMetadataData.class);
- if (res.isRight()) {
- return res.right().value();
- }
- service.setAllVersions(res.left().value());
- return TitanOperationStatus.OK;
- }
-
- public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) {
- List<ArtifactDefinition> artifacts = new ArrayList<>();
- return Either.left(artifacts);
- }
-
- @Override
- public boolean isComponentExist(String serviceId) {
- return isComponentExist(serviceId, NodeTypeEnum.Service);
- }
-
- // @SuppressWarnings("unchecked")
- // @Override
- // public <T> Either<T, StorageOperationStatus> cloneComponent(T other,
- // String version, boolean inTransaction) {
- // return (Either<T, StorageOperationStatus>) cloneService((Service)other,
- // version, inTransaction);
- // }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) {
- return (Either<T, StorageOperationStatus>) cloneService((Service) other, version, targetLifecycle, inTransaction);
- }
-
- @Override
- public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction) {
- return increaseAndGetComponentInstanceCounter(componentId, NodeTypeEnum.Service, inTransaction);
- }
-
- @Override
- protected StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type) {
- List<CategoryDefinition> newcategories = component.getCategories();
- CategoryDefinition newCat = newcategories.get(0);
- CategoryDefinition currentCategory = currentComponent.getCategories().get(0);
-
- StorageOperationStatus status = StorageOperationStatus.OK;
- if (newCat != null && newCat.getName() != null && false == newCat.getName().equals(currentCategory.getName())) {
- log.debug("Going to update the category of the resource from {} to {}",currentCategory,newCat.getName());
-
- status = moveCategoryEdge(component, componentData, newCat, type);
- log.debug("Going to update the category of the resource from {} to {}. status is {}",currentCategory,newCat.getName(),status);
- }
- return status;
- }
-
- @Override
- protected <T extends Component> StorageOperationStatus updateDerived(Component component, Component currentComponent, ComponentMetadataData componentData, Class<T> clazz) {
- log.debug("Derived class isn't supported for resource");
- return null;
- }
-
- @Override
- public Service getDefaultComponent() {
- return new Service();
- }
-
- @Override
- public Either<Component, StorageOperationStatus> getMetadataComponent(String id, boolean inTransaction) {
- return getMetadataComponent(id, NodeTypeEnum.Service, inTransaction);
- }
-
- @Override
- Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData) {
- return convertServiceDataToService((ServiceMetadataData) componentMetadataData);
- }
-
- @Override
- public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String componentName) {
- return validateComponentNameUniqueness(componentName, titanGenericDao, NodeTypeEnum.Service);
- }
-
- @Override
- public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete, boolean inTransaction) {
- return internalMarkComponentToDelete(componentToDelete, inTransaction);
- }
-
- @Override
- public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
- return isComponentInUse(componentId, NodeTypeEnum.Service);
- }
-
- @Override
- public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion() {
- return getAllComponentsMarkedForDeletion(NodeTypeEnum.Service);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTransaction) {
-
- Either<Service, StorageOperationStatus> component = getService(id, componentParametersView, inTransaction);
- if (component.isRight()) {
- return Either.right(component.right().value());
- }
- return (Either<T, StorageOperationStatus>) component;
- }
-
- public Either<Service, StorageOperationStatus> updateService(Service service, boolean inTransaction, ComponentParametersView filterResultView) {
- return (Either<Service, StorageOperationStatus>) updateComponentFilterResult(service, inTransaction, titanGenericDao, service.getClass(), NodeTypeEnum.Service, filterResultView);
- }
-
- @Override
- protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterResultView) {
- return (Either<T, StorageOperationStatus>) updateService((Service) component, inTransaction, filterResultView);
- }
-
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java
deleted file mode 100644
index 5674a6ef0c..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator;
-import org.springframework.stereotype.Component;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-@Component("tosca-path-calculator")
-public class ToscaDefinitionPathCalculatorImpl implements ToscaDefinitionPathCalculator {
-
- @Override
- public List<String> calculateToscaDefinitionPath(ComponentInstance componentInstance, GraphEdge edge) {
- String ownerId = getCapReqOwner(edge);
- String instanceId = componentInstance.getUniqueId();
- return ownerId.equals(instanceId) ? Collections.singletonList(instanceId) : Arrays.asList(instanceId, ownerId);
- }
-
- private String getCapReqOwner(GraphEdge edge) {
- String ownerIdKey = GraphEdgePropertiesDictionary.OWNER_ID.getProperty();
- return (String)edge.getProperties().get(ownerIdKey);
- }
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java
index 81ca98444c..62ab886472 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java
@@ -68,11 +68,6 @@ public class UserAdminOperation implements IUserAdminOperation {
private static Logger log = LoggerFactory.getLogger(UserAdminOperation.class.getName());
@Override
- public Either<User, ActionStatus> getInactiveUserData(String id) {
- return getUserData(id, false, false);
- }
-
- @Override
public Either<User, ActionStatus> getUserData(String id, boolean inTransaction) {
return getUserData(id, true, inTransaction);
}
@@ -380,16 +375,6 @@ public class UserAdminOperation implements IUserAdminOperation {
return result;
}
- @Override
- public Either<List<User>, ActionStatus> getAllUsers() {
- try {
- Either<List<UserData>, TitanOperationStatus> userNodes = titanGenericDao.getAll(NodeTypeEnum.User, UserData.class);
- return convertToUsers("", userNodes);
- } finally {
- titanGenericDao.commit();
- }
- }
-
private Either<User, ActionStatus> getUserNotFoundError(String uid, TitanOperationStatus status) {
if (status == TitanOperationStatus.NOT_FOUND) {
log.debug("User with userId {} not found", uid);
@@ -427,96 +412,4 @@ public class UserAdminOperation implements IUserAdminOperation {
return userData;
}
- @Override
- public Either<ImmutablePair<User, FunctionalMenuInfo>, ActionStatus> getUserDataWithFunctionalMenu(String userId) {
-
- Either<User, ActionStatus> userData = getUserData(userId, true, true);
-
- if (userData.isRight()) {
- return Either.right(userData.right().value());
- }
- User user = userData.left().value();
- Either<UserFunctionalMenuData, TitanOperationStatus> functionalMenu = getFunctionalMenu(userId);
-
- FunctionalMenuInfo functionalMenuInfo = new FunctionalMenuInfo();
- if (functionalMenu.isRight()) {
- TitanOperationStatus status = functionalMenu.right().value();
- if (status != TitanOperationStatus.NOT_FOUND) {
- return Either.right(ActionStatus.GENERAL_ERROR);
- }
- } else {
- UserFunctionalMenuData userFunctionalMenuData = functionalMenu.left().value();
- functionalMenuInfo.setFunctionalMenu(userFunctionalMenuData.getFunctionalMenu());
- }
-
- ImmutablePair<User, FunctionalMenuInfo> result = new ImmutablePair<User, FunctionalMenuInfo>(user, functionalMenuInfo);
-
- return Either.left(result);
- }
-
- public Either<UserFunctionalMenuData, TitanOperationStatus> getFunctionalMenu(String userId) {
-
- Either<UserFunctionalMenuData, TitanOperationStatus> result;
- if (userId == null) {
- log.info("User userId is empty");
- result = Either.right(TitanOperationStatus.NOT_FOUND);
- return result;
- }
- userId = userId.toLowerCase();
- String uid = UniqueIdBuilder.buildUserFunctionalMenuUid(userId);
-
- Either<UserFunctionalMenuData, TitanOperationStatus> either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.UserFunctionalMenu), uid, UserFunctionalMenuData.class);
-
- return either;
- }
-
- public Either<FunctionalMenuInfo, TitanOperationStatus> createOrUpdateFunctionalMenu(String userId, String newFunctionalMenu) {
-
- Either<UserFunctionalMenuData, TitanOperationStatus> functionalMenu = getFunctionalMenu(userId);
-
- if (functionalMenu.isRight()) {
- TitanOperationStatus status = functionalMenu.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- String uid = UniqueIdBuilder.buildUserFunctionalMenuUid(userId);
- UserFunctionalMenuData functionalMenuData = new UserFunctionalMenuData(newFunctionalMenu, uid);
-
- Either<UserFunctionalMenuData, TitanOperationStatus> createNode = titanGenericDao.createNode(functionalMenuData, UserFunctionalMenuData.class);
-
- if (createNode.isRight()) {
- return Either.right(createNode.right().value());
- } else {
- return Either.left(convert(createNode.left().value()));
- }
-
- } else {
- return Either.right(status);
- }
-
- } else {
- UserFunctionalMenuData userFunctionalMenuData = functionalMenu.left().value();
- userFunctionalMenuData.setFunctionalMenu(newFunctionalMenu);
- Either<UserFunctionalMenuData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(userFunctionalMenuData, UserFunctionalMenuData.class);
-
- if (updateNode.isRight()) {
- return Either.right(updateNode.right().value());
- } else {
- return Either.left(convert(updateNode.left().value()));
- }
- }
-
- }
-
- private FunctionalMenuInfo convert(UserFunctionalMenuData functionalMenuData) {
-
- if (functionalMenuData == null) {
- return null;
- }
-
- FunctionalMenuInfo functionalMenuInfo = new FunctionalMenuInfo();
- functionalMenuInfo.setFunctionalMenu(functionalMenuData.getFunctionalMenu());
-
- return functionalMenuInfo;
-
- }
-
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationMalformedDataLogger.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationMalformedDataLogger.java
deleted file mode 100644
index 3cbdfc798c..0000000000
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationMalformedDataLogger.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.migration;
-
-import org.apache.commons.lang3.StringUtils;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-/**
- * to be moved with all operations to the migration project
- */
-
-public class MigrationMalformedDataLogger {
-
- private static Logger log = LoggerFactory.getLogger(MigrationMalformedDataLogger.class);
- private static Set<String> malformedVFs = new HashSet<>();
-
- public static void reportMalformedVF(String vfId, String errorMsg) {
- log.error(errorMsg);
- malformedVFs.add(vfId);
- }
-
- public static void logMalformedDataMsg(String errorMsg) {
- log.error(errorMsg);
- }
-
- public static void logIfServiceUsingMalformedVfs(Component service) {
- List<ComponentInstance> componentInstances = service.getComponentInstances();
- if (componentInstances != null && !componentInstances.isEmpty() && !malformedVFs.isEmpty()) {
- Set<String> serviceInstances = componentInstances.stream().map(ComponentInstance::getComponentUid).collect(Collectors.toSet());
- serviceInstances.retainAll(malformedVFs);
- if (!serviceInstances.isEmpty()) {
- log.error(String.format("Service %s with id %s and version %s is using malformed VFs: %s", service.getName(),
- service.getVersion(),
- service.getUniqueId(),
- StringUtils.join(serviceInstances, ',')));
- }
- }
- }
-
-
-}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java
index fe5d79a266..01c9eefb20 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java
@@ -20,20 +20,16 @@
package org.openecomp.sdc.be.model.operations.utils;
+import fj.data.Either;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
-import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
-import org.openecomp.sdc.be.model.operations.api.IServiceOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import fj.data.Either;
-
public class ComponentValidationUtils {
private static Logger log = LoggerFactory.getLogger(ComponentValidationUtils.class.getName());
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaFunctions.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaFunctions.java
new file mode 100644
index 0000000000..e6969bc5c2
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaFunctions.java
@@ -0,0 +1,19 @@
+package org.openecomp.sdc.be.model.tosca;
+
+/**
+ * tosca functions supported by sdc
+ */
+public enum ToscaFunctions {
+
+ GET_INPUT("get_input");
+
+ private String functionName;
+
+ ToscaFunctions(String functionName) {
+ this.functionName = functionName;
+ }
+
+ public String getFunctionName() {
+ return functionName;
+ }
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverter.java
new file mode 100644
index 0000000000..2d389f5fe5
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverter.java
@@ -0,0 +1,130 @@
+package org.openecomp.sdc.be.model.tosca.converters;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.google.gson.stream.JsonReader;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.common.util.JsonUtils;
+
+import java.io.StringReader;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class DataTypePropertyConverter {
+
+ private static final DataTypePropertyConverter INSTANCE = new DataTypePropertyConverter();
+ private static final JsonParser jsonParser = new JsonParser();
+ private static final Gson gson = new Gson();
+
+ private DataTypePropertyConverter() {
+ }
+
+ public static DataTypePropertyConverter getInstance() {
+ return INSTANCE;
+ }
+
+ /**
+ *
+ * @param propertyDataType the data type
+ * @param dataTypes all data types in the system mapped by their name
+ * @return a json representation of all the given data type properties default values and recursively their data type properties
+ */
+ public String getDataTypePropertiesDefaultValuesRec(String propertyDataType, Map<String, DataTypeDefinition> dataTypes) {
+ JsonObject defaultValues = getDataTypePropsDefaultValuesRec(propertyDataType, dataTypes);
+ return !defaultValues.isJsonNull() ? gson.toJson(defaultValues) : null;
+ }
+
+ /**
+ * Takes a json representation of a tosca property value and merges all the default values of the property data type
+ * @param value the json representation of a tosca property value
+ * @param propertyDataType data type from which to merge default values
+ * @param dataTypes all data types in the system mapped by their name
+ * for example: for value {a: {b: c}} we could have a default value {a: {d: e}} (property a has two sub properties but only b was overridden)
+ * so the complete value is {a: {b: c, d: e}}
+ */
+ public void mergeDataTypeDefaultValuesWithPropertyValue(JsonObject value, String propertyDataType, Map<String, DataTypeDefinition> dataTypes) {
+ JsonObject dataTypeDefaultValues = getDataTypePropsDefaultValuesRec(propertyDataType, dataTypes);
+ mergeDefaultValuesRec(dataTypeDefaultValues, value);
+ }
+
+ private void mergeDefaultValuesRec(JsonObject defaultValue, JsonObject value) {
+ if (ToscaConverterUtils.isGetInputValue(value)) {
+ return;
+ }
+ for (Map.Entry<String, JsonElement> defVal : defaultValue.entrySet()) {
+ mergeDefaultValue(value, defVal.getKey(), defVal.getValue());
+ }
+ }
+
+ private void mergeDefaultValue(JsonObject value, String propName, JsonElement defValue) {
+ if (defValueWasNotOverridden(value, propName)) {
+ value.add(propName, defValue);
+ } else if (notPrimitivePropValue(value, defValue, propName)) {
+ JsonElement propValue = value.get(propName);
+ mergeDefaultValuesRec(defValue.getAsJsonObject(), propValue.getAsJsonObject());
+ }
+ }
+
+ private boolean notPrimitivePropValue(JsonObject value, JsonElement defValue, String propName) {
+ return value.get(propName).isJsonObject() && defValue.isJsonObject();
+ }
+
+ private boolean defValueWasNotOverridden(JsonObject value, String propName) {
+ return !value.has(propName);
+ }
+
+ private JsonObject getDataTypePropsDefaultValuesRec(String propertyDataType, Map<String, DataTypeDefinition> dataTypes) {
+ Map<String, PropertyDefinition> allParentsProps = getAllDataTypeProperties(dataTypes.get(propertyDataType));
+ JsonObject dataTypeDefaultsJson = new JsonObject();
+ for (Map.Entry<String, PropertyDefinition> propertyEntry : allParentsProps.entrySet()) {
+ PropertyDefinition propertyDefinition = propertyEntry.getValue();
+ addDefaultValueToJson(dataTypes, dataTypeDefaultsJson, propertyDefinition);
+ }
+ return dataTypeDefaultsJson;
+ }
+
+ private void addDefaultValueToJson(Map<String, DataTypeDefinition> dataTypes, JsonObject dataTypePropsDefaults, PropertyDefinition propertyDefinition) {
+ String propName = propertyDefinition.getName();
+ JsonElement defVal = getDefaultValue(dataTypes, dataTypePropsDefaults, propertyDefinition);
+ if (!JsonUtils.isEmptyJson(defVal)) {
+ dataTypePropsDefaults.add(propName, defVal);
+ }
+ }
+
+ private JsonElement getDefaultValue(Map<String, DataTypeDefinition> dataTypes, JsonObject dataTypePropsDefaults, PropertyDefinition propertyDefinition) {
+ JsonElement defVal = new JsonObject();
+ String propName = propertyDefinition.getName();
+ String propDefaultVal = propertyDefinition.getDefaultValue();
+ if(!JsonUtils.containsEntry(dataTypePropsDefaults, propName) && propDefaultVal != null){
+ defVal = convertToJson(propDefaultVal);
+ } else if (!JsonUtils.containsEntry(dataTypePropsDefaults, propName)) {
+ defVal = getDataTypePropsDefaultValuesRec(propertyDefinition.getType(), dataTypes);
+ }
+ return defVal;
+ }
+
+ private JsonElement convertToJson(String propDefaultVal) {
+ JsonReader jsonReader = new JsonReader(new StringReader(propDefaultVal));
+ jsonReader.setLenient(true);
+ return jsonParser.parse(jsonReader);
+ }
+
+ private Map<String, PropertyDefinition> getAllDataTypeProperties(DataTypeDefinition dataTypeDefinition) {
+ Map<String, PropertyDefinition> allParentsProps = new HashMap<>();
+ while (dataTypeDefinition != null) {
+
+ List<PropertyDefinition> currentParentsProps = dataTypeDefinition.getProperties();
+ if (currentParentsProps != null) {
+ currentParentsProps.stream().forEach(p -> allParentsProps.put(p.getName(), p));
+ }
+
+ dataTypeDefinition = dataTypeDefinition.getDerivedFrom();
+ }
+ return allParentsProps;
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java
index 6e077d60a1..9922c0f05d 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatJsonConverter.java
@@ -39,12 +39,15 @@ public class HeatJsonConverter implements PropertyValueConverter {
@Override
public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) {
- String coverted = ValidationUtils.removeNoneUtf8Chars(original);
- coverted = ValidationUtils.removeHtmlTagsOnly(coverted);
- coverted = ValidationUtils.normaliseWhitespace(coverted);
- coverted = ValidationUtils.stripOctets(coverted);
+ if (original == null) {
+ return null;
+ }
+ String converted = ValidationUtils.removeNoneUtf8Chars(original);
+ converted = ValidationUtils.removeHtmlTagsOnly(converted);
+ converted = ValidationUtils.normaliseWhitespace(converted);
+ converted = ValidationUtils.stripOctets(converted);
// As opposed to string converter, keeping the " and ' symbols
- return coverted;
+ return converted;
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java
index c8fac11b3a..3f2b6eabf7 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java
@@ -45,7 +45,6 @@ public class HeatStringConverter implements PropertyValueConverter {
coverted = ValidationUtils.normaliseWhitespace(coverted);
coverted = ValidationUtils.stripOctets(coverted);
coverted = ValidationUtils.removeHtmlTagsOnly(coverted);
- coverted = coverted.replaceAll("\"", "").replaceAll("\'", "");
}
return coverted;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaConverterUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaConverterUtils.java
new file mode 100644
index 0000000000..159addcbc9
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaConverterUtils.java
@@ -0,0 +1,13 @@
+package org.openecomp.sdc.be.model.tosca.converters;
+
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import org.openecomp.sdc.be.model.tosca.ToscaFunctions;
+
+public class ToscaConverterUtils {
+
+ public static boolean isGetInputValue(JsonObject value) {
+ return value.get(ToscaFunctions.GET_INPUT.getFunctionName()) != null;
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java
index 0673033546..5b565bf62a 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java
@@ -193,22 +193,8 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
}
JsonObject asJsonObjectIn = entryValue.getAsJsonObject();
- DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
- Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition);
+ DataTypePropertyConverter.getInstance().mergeDataTypeDefaultValuesWithPropertyValue(asJsonObjectIn, innerType, dataTypes);
Map<String, Object> toscaObjectPresentation = new HashMap<>();
-
- for (Entry<String, PropertyDefinition> entry : allProperties.entrySet()) {
- String propName = entry.getKey();
- PropertyDefinition propertyDefinition = entry.getValue();
- JsonElement elementValue = asJsonObjectIn.get(propName);
- if(elementValue == null && propertyDefinition.getDefaultValue() != null){
- JsonReader jsonReader = new JsonReader(new StringReader(propertyDefinition.getDefaultValue()));
- jsonReader.setLenient(true);
- elementValue = jsonParser.parse(jsonReader);
- asJsonObjectIn.add(propName, elementValue);
- }
- }
-
Set<Entry<String, JsonElement>> entrySetIn = asJsonObjectIn.entrySet();
for (Entry<String, JsonElement> entry : entrySetIn) {
@@ -217,6 +203,8 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
JsonElement elementValue = entry.getValue();
Object convValue;
if (isScalarF == false) {
+ DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
+ Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition);
PropertyDefinition propertyDefinition = allProperties.get(propName);
if (propertyDefinition == null) {
log.trace("The property {} was not found under data type . Parse as map", propName);
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java
index eea11b6625..b24d6d8285 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperationTest.java
@@ -20,37 +20,20 @@
package org.openecomp.sdc.be.model.operations.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.ModelTestBase;
-import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil;
import org.openecomp.sdc.be.resources.data.UserData;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.thinkaurelius.titan.core.TitanGraph;
-//import com.tinkerpop.blueprints.Vertex;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
+import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-context-test.xml")
@@ -62,9 +45,6 @@ public class AdditionalInformationOperationTest extends ModelTestBase {
@javax.annotation.Resource(name = "titan-generic-dao")
private TitanGenericDao titanDao;
- @javax.annotation.Resource(name = "resource-operation")
- private ResourceOperation resourceOperation;
-
@javax.annotation.Resource(name = "additional-information-operation")
private IAdditionalInformationOperation additionalInformationOperation;
@@ -89,64 +69,6 @@ public class AdditionalInformationOperationTest extends ModelTestBase {
}
- private int getNumberOfVerticesOnGraph() {
- Either<TitanGraph, TitanOperationStatus> graphResult = titanDao.getGraph();
- TitanGraph graph = graphResult.left().value();
-
- int i = 0;
- Iterable<TitanVertex> vertices = graph.query().vertices();
- if (vertices != null) {
- Iterator<TitanVertex> iterator = vertices.iterator();
- while (iterator.hasNext()) {
- TitanVertex vertex = iterator.next();
- i++;
- }
-
- }
-
- titanDao.commit();
-
- return i;
- }
-
- @Test
- public void testCreateAndDeleteResource() {
-
- int before = getNumberOfVerticesOnGraph();
-
- Resource newResource = createResource(USER_ID, CATEGORY_NAME, "testCreateAndDeleteResource", "0.1", null, false, true);
- String resourceId = newResource.getUniqueId();
-
- Either<Resource, StorageOperationStatus> deleteResource = resourceOperation.deleteResource(resourceId);
- assertTrue(deleteResource.isLeft());
-
- int after = getNumberOfVerticesOnGraph();
-
- assertEquals("check number of vertices not changed", before, after);
- }
-
- private Resource buildResourceMetadata(String userId, String category, String resourceName, String resourceVersion) {
-
- Resource resource = new Resource();
- resource.setName(resourceName);
- resource.setVersion(resourceVersion);
- ;
- resource.setDescription("description 1");
- resource.setAbstract(false);
- resource.setCreatorUserId(userId);
- resource.setContactId("contactId@sdc.com");
- resource.setVendorName("vendor 1");
- resource.setVendorRelease("1.0.0");
- String[] categoryArr = category.split("/");
- resource.addCategory(categoryArr[0], categoryArr[1]);
- resource.setIcon("images/my.png");
- // List<String> tags = new ArrayList<String>();
- // tags.add("TAG1");
- // tags.add("TAG2");
- // resource.setTags(tags);
- return resource;
- }
-
private UserData deleteAndCreateUser(String userId, String firstName, String lastName) {
UserData userData = new UserData();
userData.setUserId(userId);
@@ -165,26 +87,4 @@ public class AdditionalInformationOperationTest extends ModelTestBase {
OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao);
}
- public Resource createResource(String userId, String category, String resourceName, String resourceVersion, String parentResourceName, boolean isAbstract, boolean isHighestVersion) {
-
- List<String> derivedFrom = new ArrayList<String>();
- if (parentResourceName != null) {
- derivedFrom.add(parentResourceName);
- }
- Resource resource = buildResourceMetadata(userId, category, resourceName, resourceVersion);
-
- resource.setAbstract(isAbstract);
- resource.setHighestVersion(isHighestVersion);
-
- Either<Resource, StorageOperationStatus> result = resourceOperation.createResource(resource, true);
-
- assertTrue(result.isLeft());
- Resource resultResource = result.left().value();
-
- assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultResource.getLifecycleState());
-
- return resultResource;
-
- }
-
}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java
index 875c34b780..1082b44e5b 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperationTest.java
@@ -20,18 +20,10 @@
package org.openecomp.sdc.be.model.operations.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import fj.data.Either;
import org.junit.Before;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
@@ -46,18 +38,8 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.ModelTestBase;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
+import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
-import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.model.operations.impl.RequirementOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil;
import org.openecomp.sdc.be.resources.data.ArtifactData;
import org.openecomp.sdc.be.resources.data.HeatParameterData;
@@ -70,7 +52,12 @@ import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import fj.data.Either;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-context-test.xml")
@@ -81,37 +68,13 @@ public class ArtifactOperationTest extends ModelTestBase {
@javax.annotation.Resource(name = "titan-generic-dao")
private TitanGenericDao titanDao;
- @javax.annotation.Resource(name = "service-operation")
- private ServiceOperation serviceOperation;
-
- @javax.annotation.Resource
- private IGraphLockOperation graphLockOperation;
+ @javax.annotation.Resource(name = "tosca-operation-facade")
+ private ToscaOperationFacade toscaOperationFacade;
@javax.annotation.Resource
private ArtifactOperation artifactOperation;
- @javax.annotation.Resource(name = "requirement-operation")
- private RequirementOperation requirementOperation;
-
- @javax.annotation.Resource(name = "resource-operation")
- private ResourceOperation resourceOperation;
-
- @javax.annotation.Resource(name = "property-operation")
- private PropertyOperation propertyOperation;
-
- @javax.annotation.Resource(name = "capability-operation")
- private CapabilityOperation capabilityOperation;
-
- @javax.annotation.Resource(name = "capability-type-operation")
- private CapabilityTypeOperation capabilityTypeOperation;
-
- @javax.annotation.Resource(name = "component-instance-operation")
- private ComponentInstanceOperation resourceInstanceOperation;
-
- @javax.annotation.Resource(name = "lifecycle-operation")
- private LifecycleOperation lifecycleOperation;
-
- private static Logger log = LoggerFactory.getLogger(ServiceOperation.class.getName());
+ private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName());
private static String RESOURCE_ID = "resourceId";
private static String RESOURCE_ID_2 = "resourceId2";
@@ -132,6 +95,7 @@ public class ArtifactOperationTest extends ModelTestBase {
}
@Test
+ @Ignore
public void testAddArtifactToServiceVersionAndUUIDNotNull() {
CategoryDefinition category = new CategoryDefinition();
category.setName(CATEGORY_NAME);
@@ -149,7 +113,7 @@ public class ArtifactOperationTest extends ModelTestBase {
assertNotNull("add informational artifact version : " + artifactInfo.getArtifactUUID(), artifactInfo.getArtifactUUID());
- Either<Service, StorageOperationStatus> service = serviceOperation.getService(serviceId);
+ Either<Service, StorageOperationStatus> service = toscaOperationFacade.getToscaFullElement(serviceId);
assertTrue(service.isLeft());
Map<String, ArtifactDefinition> artifacts = service.left().value().getArtifacts();
@@ -159,23 +123,24 @@ public class ArtifactOperationTest extends ModelTestBase {
artifactOperation.removeArifactFromResource(serviceId, artifactId, NodeTypeEnum.Service, true, false);
}
- service = serviceOperation.getService(serviceId);
+ service = toscaOperationFacade.getToscaFullElement(serviceId);
assertTrue(service.isLeft());
artifacts = service.left().value().getArtifacts();
assertEquals(0, artifacts.size());
- Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(serviceId);
+ Either<Service, StorageOperationStatus> serviceDelete = toscaOperationFacade.deleteToscaComponent(serviceId);
Either<List<ArtifactData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, null, ArtifactData.class);
assertTrue(byCriteria.isRight());
assertEquals(TitanOperationStatus.NOT_FOUND, byCriteria.right().value());
- serviceOperation.deleteService(serviceAfterSave.getUniqueId());
+ toscaOperationFacade.deleteToscaComponent(serviceId);
}
@Test
+ @Ignore
public void testUpdateArtifactToServiceVersionNotChanged() {
CategoryDefinition category = new CategoryDefinition();
category.setName(CATEGORY_NAME);
@@ -200,7 +165,7 @@ public class ArtifactOperationTest extends ModelTestBase {
assertEquals("add informational artifact version : " + newVersion, newVersion, version);
assertEquals("add informational artifact uuid : " + newArtUuid, newArtUuid, artUuid);
- Either<Service, StorageOperationStatus> service = serviceOperation.getService(serviceId);
+ Either<Service, StorageOperationStatus> service = toscaOperationFacade.getToscaFullElement(serviceId);
assertTrue(service.isLeft());
Map<String, ArtifactDefinition> artifacts = service.left().value().getArtifacts();
@@ -210,19 +175,19 @@ public class ArtifactOperationTest extends ModelTestBase {
artifactOperation.removeArifactFromResource(serviceId, artifactId, NodeTypeEnum.Service, true, false);
}
- service = serviceOperation.getService(serviceId);
+ service = toscaOperationFacade.getToscaFullElement(serviceId);
assertTrue(service.isLeft());
artifacts = service.left().value().getArtifacts();
assertEquals(0, artifacts.size());
- Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(serviceId);
+ Either<Service, StorageOperationStatus> serviceDelete = toscaOperationFacade.deleteToscaComponent(serviceId);
Either<List<ArtifactData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, null, ArtifactData.class);
assertTrue(byCriteria.isRight());
assertEquals(TitanOperationStatus.NOT_FOUND, byCriteria.right().value());
- serviceOperation.deleteService(serviceAfterSave.getUniqueId());
+ toscaOperationFacade.deleteToscaComponent(serviceAfterSave.getUniqueId());
}
@@ -469,7 +434,7 @@ public class ArtifactOperationTest extends ModelTestBase {
service.setHighestVersion(isHighestVersion);
- Either<Service, StorageOperationStatus> result = serviceOperation.createService(service, true);
+ Either<Service, StorageOperationStatus> result = toscaOperationFacade.createToscaComponent(service);
log.info(result.toString());
assertTrue(result.isLeft());
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java
deleted file mode 100644
index f07115af5b..0000000000
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationSpringTest.java
+++ /dev/null
@@ -1,513 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.UUID;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import javax.annotation.Resource;
-
-import org.apache.tinkerpop.gremlin.structure.io.IoCore;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.ModelTestBase;
-import org.openecomp.sdc.be.model.PropertyConstraint;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
-import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ServiceOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil;
-import org.openecomp.sdc.be.model.operations.impl.util.ResourceCreationUtils;
-import org.openecomp.sdc.be.model.tosca.ToscaType;
-import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint;
-import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint;
-import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint;
-import org.openecomp.sdc.be.resources.data.CapabilityData;
-import org.openecomp.sdc.be.resources.data.CapabilityInstData;
-import org.openecomp.sdc.be.resources.data.PropertyValueData;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
-import org.openecomp.sdc.be.resources.data.UserData;
-import org.openecomp.sdc.be.unittests.utils.FactoryUtils;
-import org.openecomp.sdc.be.unittests.utils.FactoryUtils.Constants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration("classpath:application-context-test.xml")
-public class ComponentInstanceOperationSpringTest extends ModelTestBase {
- private static Logger log = LoggerFactory.getLogger(ComponentInstanceOperationSpringTest.class.getName());
- @Resource(name = "component-instance-operation")
- private ComponentInstanceOperation componentInstanceOperation;
-
- @Resource(name = "component-instance-operation")
- private ComponentInstanceOperation resourceInstanceOperation;
-
- @Resource(name = "capability-type-operation")
- private CapabilityTypeOperation capabilityTypeOperation;
-
- @Resource(name = "capability-operation")
- public CapabilityOperation capabilityOperation;
-
- @Resource(name = "service-operation")
- private ServiceOperation serviceOperation;
-
- @Resource(name = "resource-operation")
- private ResourceOperation resourceOperation;
-
- @Resource(name = "property-operation")
- private PropertyOperation propertyOperation;
-
- @Resource(name = "lifecycle-operation")
- private LifecycleOperation lifecycleOperation;
-
- TitanGenericDao titanGenericDao;
-
- private static String CATEGORY_NAME = "category/mycategory";
-
- User rfcUser;
-
- @BeforeClass
- public static void setupBeforeClass() {
- ModelTestBase.init();
-
- }
-
- @Before
- public void cleanUp() {
- titanGenericDao = componentInstanceOperation.titanGenericDao;
- Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
- TitanGraph graph = graphResult.left().value();
-
- Iterable<TitanVertex> vertices = graph.query().vertices();
- if (vertices != null) {
- Iterator<TitanVertex> iterator = vertices.iterator();
- while (iterator.hasNext()) {
- TitanVertex vertex = iterator.next();
- vertex.remove();
- }
-
- }
- titanGenericDao.commit();
- deleteAndCreateCategory(CATEGORY_NAME);
- UserData modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "rfc", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
- rfcUser = convertUserDataToUser(modifierData);
- }
-
- @Test
- @Ignore
- public void testAddCapabilityPropertyValuesToResourceInstance() {
- String rootName = "Root123";
- org.openecomp.sdc.be.model.Resource rootResource = createResource(rfcUser.getUserId(), CATEGORY_NAME, rootName, "1.0", null, false, true);
-
- // certification request
- Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, rootResource, rfcUser, rfcUser, false);
- assertTrue(requestCertificationResult.isLeft());
-
- org.openecomp.sdc.be.model.Resource resultResource = (org.openecomp.sdc.be.model.Resource) requestCertificationResult.left().value();
-
- // start certification
- Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource, rfcUser, rfcUser, false);
- assertEquals(true, startCertificationResult.isLeft());
-
- Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> certifiedResourceRes = lifecycleOperation.certifyComponent(NodeTypeEnum.Resource, rootResource, rfcUser, rfcUser, false);
- assertTrue(certifiedResourceRes.isLeft());
-
- CapabilityTypeDefinition capabilityType = buildCapabilityType();
- Either<CapabilityTypeDefinition, StorageOperationStatus> capabilityTypeRes = capabilityTypeOperation.addCapabilityType(capabilityType);
- assertTrue(capabilityTypeRes.isLeft());
-
- CapabilityData capData = FactoryUtils.createCapabilityData();
- CapabilityDefinition capabilityDefinitionRoot = FactoryUtils.convertCapabilityDataToCapabilityDefinitionRoot(capData);
-
- Either<CapabilityDefinition, StorageOperationStatus> addCapabilityRootRes = capabilityOperation.addCapability((String) certifiedResourceRes.left().value().getUniqueId(), capabilityDefinitionRoot.getName(), capabilityDefinitionRoot);
- assertTrue(addCapabilityRootRes.isLeft());
-
- String resourceName = "tosca.nodes.Apache.2.0";
-
- CapabilityDefinition capabilityDefinition = FactoryUtils.convertCapabilityDataToCapabilityDefinitionAddProperties(capData);
- org.openecomp.sdc.be.model.Resource resource = createResource(rfcUser.getUserId(), CATEGORY_NAME, resourceName, "0.1", rootName, false, true);
-
- Either<CapabilityDefinition, StorageOperationStatus> addCapabilityRes = capabilityOperation.addCapability((String) resource.getUniqueId(), capabilityDefinition.getName(), capabilityDefinition);
- assertTrue(addCapabilityRes.isLeft());
- List<ComponentInstanceProperty> properties = addCapabilityRes.left().value().getProperties();
- assertTrue(properties.size() == 2);
-
- Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> clonedResourceRes = resourceOperation.cloneComponent(resource, "0.2", false);
- assertTrue(clonedResourceRes.isLeft());
- org.openecomp.sdc.be.model.Resource clonedResource = clonedResourceRes.left().value();
-
- ComponentInstance instance = buildResourceInstance(clonedResource.getUniqueId(), "1", "tosca.nodes.Apache");
-
- Service origService = createService(rfcUser.getUserId(), CATEGORY_NAME, "my-service", "1.0", true);
- Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(), false);
- assertTrue(service2.isLeft());
- origService = service2.left().value();
-
- Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
- String json = prettyGson.toJson(origService);
- log.debug(json);
-
- Service fullService = origService;
-
- Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) origService.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false);
- assertTrue(status.isLeft());
-
- ComponentInstance resourceInstance = status.left().value();
- CapabilityDefinition capability = addCapabilityRes.left().value();
- capability.setName(capabilityDefinition.getName());
- List<ComponentInstanceProperty> propertyValues = FactoryUtils.createComponentInstancePropertyList();
- capability.setProperties(propertyValues);
-
- Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> addCPVsToRiRes = componentInstanceOperation.addCapabilityPropertyValuesToResourceInstance(resourceInstance.getUniqueId(), capability, true);
- assertTrue(addCPVsToRiRes.isLeft());
-
- Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", false);
- assertTrue(createService.isLeft());
- Map<String, List<CapabilityDefinition>> capabilitiesMap = createService.left().value().getCapabilities();
- assertTrue(capabilitiesMap != null && capabilitiesMap.size() == 1);
- Map<String, CapabilityDefinition> capabilities = capabilitiesMap.values().iterator().next().stream().collect(Collectors.toMap(CapabilityDefinition::getName, Function.identity()));
- assertTrue(capabilities.containsKey("Cap1") && capabilities.containsKey("Cap2"));
-
- // String outputFile = exportGraphMl();
-
- }
-
- public String exportGraphMl() {
- String result = null;
- String outputFile = "C:\\Output" + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml";
- TitanGraph graph = titanGenericDao.getGraph().left().value();
- try {
- try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) {
- graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph);
- }
- result = outputFile;
- graph.tx().commit();
- } catch (Exception e) {
- graph.tx().rollback();
- e.printStackTrace();
- }
- return result;
-
- }
-
- private CapabilityTypeDefinition buildCapabilityType() {
- CapabilityTypeDefinition capabilityType = new CapabilityTypeDefinition();
- Map<String, PropertyDefinition> properties = new HashMap();
-
- capabilityType.setType(Constants.DEFAULT_CAPABILITY_TYPE);
- capabilityType.setProperties(properties);
-
- PropertyDefinition host = new PropertyDefinition();
- host.setUniqueId(UUID.randomUUID().toString());
- host.setName("host");
- host.setDefaultValue("captypehost");
- host.setType("string");
-
- host.setSchema(new SchemaDefinition());
- host.getSchema().setProperty(new PropertyDataDefinition());
- host.getSchema().getProperty().setType("string");
-
- PropertyDefinition port = new PropertyDefinition();
- port.setName("port");
- port.setDefaultValue("captypeport");
- port.setUniqueId(UUID.randomUUID().toString());
- port.setType("string");
-
- port.setSchema(new SchemaDefinition());
- port.getSchema().setProperty(new PropertyDataDefinition());
- port.getSchema().getProperty().setType("string");
-
- PropertyDefinition rootproperty = new PropertyDefinition();
- rootproperty.setName("captypeproperty");
- rootproperty.setDefaultValue("captypevalue");
- rootproperty.setUniqueId(UUID.randomUUID().toString());
- rootproperty.setType("string");
-
- rootproperty.setSchema(new SchemaDefinition());
- rootproperty.getSchema().setProperty(new PropertyDataDefinition());
- rootproperty.getSchema().getProperty().setType("string");
-
- properties.put("host", host);
- properties.put("port", port);
- properties.put("captypeproperty", rootproperty);
- return capabilityType;
- }
-
- private CapabilityInstData buildCapabilityInstanceData(String resourceInstanceId, CapabilityDefinition capability) {
- CapabilityInstData capabilityInstance = new CapabilityInstData();
- Long creationTime = System.currentTimeMillis();
- String uniqueId = UniqueIdBuilder.buildCapabilityInstanceUid(resourceInstanceId, capability.getName());
- capabilityInstance.setCreationTime(creationTime);
- capabilityInstance.setModificationTime(creationTime);
- capabilityInstance.setUniqueId(uniqueId);
- return capabilityInstance;
- }
-
- private ComponentInstance buildResourceInstance(String respurceUid, String instanceNumber, String name) {
- ComponentInstance resourceInstance = new ComponentInstance();
- resourceInstance.setName(name);
- resourceInstance.setDescription("desc1");
- resourceInstance.setPosX("20");
- resourceInstance.setPosY("40");
- resourceInstance.setComponentUid(respurceUid);
- resourceInstance.setCreationTime(System.currentTimeMillis());
- resourceInstance.setModificationTime(System.currentTimeMillis());
- resourceInstance.setNormalizedName(ResourceInstanceOperationTest.normaliseComponentInstanceName(name));
- return resourceInstance;
- }
-
- public ResourceMetadataData createResource(String resourceName, TitanGenericDao titanGenericDao) {
- ResourceMetadataData serviceData1 = new ResourceMetadataData();
- serviceData1.getMetadataDataDefinition().setUniqueId(resourceName);
- Either<ResourceMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(serviceData1, ResourceMetadataData.class);
- assertTrue("check service created", createNode.isLeft());
- return createNode.left().value();
- }
-
- public ServiceMetadataData createServiceMetadataData(String serviceName, TitanGenericDao titanGenericDao) {
- ServiceMetadataData serviceData1 = new ServiceMetadataData();
- serviceData1.getMetadataDataDefinition().setUniqueId(serviceName);
- Either<ServiceMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(serviceData1, ServiceMetadataData.class);
- assertTrue("check service created", createNode.isLeft());
- return createNode.left().value();
- }
-
- public Service createService(String userId, String category, String serviceName, String serviceVersion, boolean isHighestVersion) {
- Service service = buildServiceMetadata(userId, category, serviceName, serviceVersion);
- service.setHighestVersion(isHighestVersion);
- Either<Service, StorageOperationStatus> result = serviceOperation.createService(service, true);
- assertTrue(result.isLeft());
- Service resultService = result.left().value();
- assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultService.getLifecycleState());
- return resultService;
- }
-
- private Service buildServiceMetadata(String userId, String category, String serviceName, String serviceVersion) {
- Service service = new Service();
- service.setName(serviceName);
- service.setVersion(serviceVersion);
- service.setDescription("description 1");
- service.setCreatorUserId(userId);
- service.setContactId("contactId@sdc.com");
- CategoryDefinition categoryDef = new CategoryDefinition();
- categoryDef.setName(category);
- List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(categoryDef);
- service.setCategories(categories);
- service.setIcon("images/my.png");
- List<String> tags = new ArrayList<String>();
- tags.add("TAG1");
- tags.add("TAG2");
- service.setTags(tags);
- return service;
- }
-
- private void deleteAndCreateCategory(String category) {
- String[] names = category.split("/");
- OperationTestsUtil.deleteAndCreateServiceCategory(category, titanGenericDao);
- OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanGenericDao);
- }
-
- private UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) {
- UserData userData = new UserData();
- userData.setUserId(userId);
- userData.setFirstName(firstName);
- userData.setLastName(lastName);
- if (role != null && !role.isEmpty()) {
- userData.setRole(role);
- } else {
- userData.setRole("ADMIN");
- }
- titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class);
- titanGenericDao.createNode(userData, UserData.class);
- titanGenericDao.commit();
- return userData;
- }
-
- public org.openecomp.sdc.be.model.Resource createResource(String userId, String category, String resourceName, String resourceVersion, String parentResourceName, boolean isAbstract, boolean isHighestVersion) {
-
- String propName1 = "disk_size";
- String propName2 = "num_cpus";
-
- List<String> derivedFrom = new ArrayList<String>();
- if (parentResourceName != null) {
- derivedFrom.add(parentResourceName);
- }
- org.openecomp.sdc.be.model.Resource resource = buildResourceMetadata(userId, category, resourceName, resourceVersion);
-
- resource.setAbstract(isAbstract);
- resource.setHighestVersion(isHighestVersion);
-
- Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>();
-
- PropertyDefinition property1 = new PropertyDefinition();
- property1.setDefaultValue("10");
- property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
- property1.setType(ToscaType.INTEGER.name().toLowerCase());
- List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>();
- GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0");
- log.debug("{}", propertyConstraint1);
-
- constraints.add(propertyConstraint1);
-
- LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10");
- constraints.add(propertyConstraint2);
-
- property1.setConstraints(constraints);
-
- properties.put(propName1, property1);
-
- PropertyDefinition property2 = new PropertyDefinition();
- property2.setDefaultValue("2");
- property2.setDescription("Number of (actual or virtual) CPUs associated with the Compute node.");
- property2.setType(ToscaType.INTEGER.name().toLowerCase());
- List<PropertyConstraint> constraints3 = new ArrayList<PropertyConstraint>();
- List<String> range = new ArrayList<String>();
- range.add("1");
- range.add("4");
-
- InRangeConstraint propertyConstraint3 = new InRangeConstraint(range);
- constraints3.add(propertyConstraint3);
- property2.setConstraints(constraints3);
- properties.put(propName2, property2);
-
- resource.setDerivedFrom(derivedFrom);
-
- resource.setProperties(convertMapToList(properties));
-
- Either<org.openecomp.sdc.be.model.Resource, StorageOperationStatus> result = resourceOperation.createResource(resource, true);
-
- assertTrue(result.isLeft());
- org.openecomp.sdc.be.model.Resource resultResource = result.left().value();
- assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultResource.getLifecycleState());
-
- String resourceId = resultResource.getUniqueId();
-
- Either<PropertyDefinition, StorageOperationStatus> either = propertyOperation.getPropertyOfResource(propName1, resourceId);
-
- assertTrue(either.isLeft());
- PropertyDefinition propertyDefinition = either.left().value();
- assertEquals("check property default value", property1.getDefaultValue(), propertyDefinition.getDefaultValue());
- assertEquals("check property description", property1.getDescription(), propertyDefinition.getDescription());
- assertEquals("check property type", property1.getType(), propertyDefinition.getType());
- assertEquals("check property unique id", property1.getUniqueId(), propertyDefinition.getUniqueId());
- assertEquals("check property consitraints size", property1.getConstraints().size(), propertyDefinition.getConstraints().size());
-
- return resultResource;
- }
-
- private org.openecomp.sdc.be.model.Resource buildResourceMetadata(String userId, String category, String resourceName, String resourceVersion) {
-
- org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource();
- resource.setName(resourceName);
- resource.setVersion(resourceVersion);
- ;
- resource.setDescription("description 1");
- resource.setAbstract(false);
- resource.setCreatorUserId(userId);
- resource.setContactId("contactId@sdc.com");
- resource.setVendorName("vendor 1");
- resource.setVendorRelease("1.0.0");
- resource.setToscaResourceName(resourceName);
- String[] categoryArr = category.split("/");
- resource.addCategory(categoryArr[0], categoryArr[1]);
- resource.setIcon("images/my.png");
- List<String> tags = new ArrayList<String>();
- tags.add("TAG1");
- tags.add("TAG2");
- resource.setTags(tags);
- return resource;
- }
-
- public static List<PropertyDefinition> convertMapToList(Map<String, PropertyDefinition> properties) {
- if (properties == null) {
- return null;
- }
-
- List<PropertyDefinition> definitions = new ArrayList<>();
- for (Entry<String, PropertyDefinition> entry : properties.entrySet()) {
- String name = entry.getKey();
- PropertyDefinition propertyDefinition = entry.getValue();
- propertyDefinition.setName(name);
- definitions.add(propertyDefinition);
- }
-
- return definitions;
- }
-
- private User convertUserDataToUser(UserData modifierData) {
- User modifier = new User();
- modifier.setUserId(modifierData.getUserId());
- modifier.setEmail(modifierData.getEmail());
- modifier.setFirstName(modifierData.getFirstName());
- modifier.setLastName(modifierData.getLastName());
- modifier.setRole(modifierData.getRole());
- return modifier;
- }
-}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java
deleted file mode 100644
index c77769d7d2..0000000000
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperationTest.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphNode;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.resources.data.CapabilityData;
-import org.openecomp.sdc.be.resources.data.CapabilityInstData;
-import org.openecomp.sdc.be.resources.data.RequirementData;
-import org.openecomp.sdc.be.unittests.utils.FactoryUtils;
-
-import fj.data.Either;
-
-public class ComponentInstanceOperationTest {
-
- @InjectMocks
- ComponentInstanceOperation componentInstanceOperation = new ComponentInstanceOperation();
- @InjectMocks
- private TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class);
-
- @Before
- public void beforeTest() {
- Mockito.reset(titanGenericDao);
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void testGetCapabilities() {
-
- ComponentInstance ri = FactoryUtils.createResourceInstance();
- CapabilityData capData = FactoryUtils.createCapabilityData();
- Either<List<ImmutablePair<GraphNode, GraphEdge>>, TitanOperationStatus> childNodesReturned = prepareChildNodeRetValue(capData);
-
- Mockito.when(titanGenericDao.getChildrenNodes(Mockito.anyString(), Mockito.anyString(), Mockito.any(GraphEdgeLabels.class), Mockito.any(NodeTypeEnum.class), Mockito.any())).thenReturn(childNodesReturned);
-
- // ImmutablePair<ComponentInstance, List<ImmutablePair<CapabilityData,
- // GraphEdge>>> instanceAndCapabilities =
- // componentInstanceOperation.getCapabilities(ri,
- // NodeTypeEnum.Resource);
-
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> instanceAndCapabilities = componentInstanceOperation.getCapabilities(ri, NodeTypeEnum.Resource);
-
- // assertTrue(instanceAndCapabilities.left.getUniqueId().equals(ri.getUniqueId()));
- assertTrue(instanceAndCapabilities.left().value().size() == 1);
- assertTrue(instanceAndCapabilities.left().value().get(0).left.getUniqueId().equals(capData.getUniqueId()));
-
- }
-
- @Test
- public void testGetRequirements() {
- ComponentInstance ri = FactoryUtils.createResourceInstance();
- RequirementData reqData = FactoryUtils.createRequirementData();
- Either<List<ImmutablePair<GraphNode, GraphEdge>>, TitanOperationStatus> childNodesReturned = prepareChildNodeRetValue(reqData);
-
- Mockito.when(titanGenericDao.getChildrenNodes(Mockito.anyString(), Mockito.anyString(), Mockito.any(GraphEdgeLabels.class), Mockito.any(NodeTypeEnum.class), Mockito.any())).thenReturn(childNodesReturned);
-
- // ImmutablePair<ComponentInstance, List<ImmutablePair<RequirementData,
- // GraphEdge>>> instanceAndCapabilities =
- // componentInstanceOperation.getRequirements(ri,
- // NodeTypeEnum.Resource);
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> instanceAndCapabilities = componentInstanceOperation.getRequirements(ri, NodeTypeEnum.Resource);
-
- // assertTrue(instanceAndCapabilities.left.getUniqueId().equals(ri.getUniqueId()));
- // assertTrue(instanceAndCapabilities.right.size() == 1);
- // assertTrue(instanceAndCapabilities.right.get(0).left.getUniqueId().equals(reqData.getUniqueId()));
-
- assertTrue(instanceAndCapabilities.left().value().size() == 1);
- assertTrue(instanceAndCapabilities.left().value().get(0).left.getUniqueId().equals(reqData.getUniqueId()));
-
- }
-
- private CapabilityInstData buildCapabilityInstanceData(String resourceInstanceId, CapabilityDefinition capability) {
- CapabilityInstData capabilityInstance = new CapabilityInstData();
- Long creationTime = System.currentTimeMillis();
- String uniqueId = UniqueIdBuilder.buildCapabilityInstanceUid(resourceInstanceId, capability.getName());
-
- capabilityInstance.setCreationTime(creationTime);
- capabilityInstance.setModificationTime(creationTime);
- capabilityInstance.setUniqueId(uniqueId);
-
- return capabilityInstance;
- }
-
- private Either<List<ImmutablePair<GraphNode, GraphEdge>>, TitanOperationStatus> prepareChildNodeRetValue(GraphNode data) {
- ImmutablePair<GraphNode, GraphEdge> pair = new ImmutablePair<>(data, FactoryUtils.createGraphEdge());
- List<ImmutablePair<GraphNode, GraphEdge>> retList = new ArrayList<>();
- retList.add(pair);
- return Either.left(retList);
- }
-
-}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java
deleted file mode 100644
index 061393645a..0000000000
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperationTest.java
+++ /dev/null
@@ -1,359 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
-
-import com.thinkaurelius.titan.core.TitanTransaction;
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.ComponentParametersView;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.operations.api.ICapabilityOperation;
-import org.openecomp.sdc.be.model.operations.api.IRequirementOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.resources.data.CapabilityData;
-import org.openecomp.sdc.be.resources.data.CapabilityInstData;
-import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
-import org.openecomp.sdc.be.resources.data.PropertyData;
-import org.openecomp.sdc.be.resources.data.PropertyValueData;
-import org.openecomp.sdc.be.resources.data.RequirementData;
-import org.openecomp.sdc.be.unittests.utils.FactoryUtils;
-
-import fj.data.Either;
-
-public class ComponentOperationTest {
- @InjectMocks
- ComponentOperation compOperation = getAnnonimusImpl();
-
- ComponentInstanceOperation componentInstanceOperation = Mockito.mock(ComponentInstanceOperation.class);
- TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class);
- ICapabilityOperation capabilityOperation = Mockito.mock(ICapabilityOperation.class);
- IRequirementOperation requirementOperation = Mockito.mock(IRequirementOperation.class);
-
- @Before
- public void beforeTest() {
- Mockito.reset(componentInstanceOperation, requirementOperation, capabilityOperation);
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void testGetCapabilities() {
- Resource vf = FactoryUtils.createVF();
- ComponentInstance ri = FactoryUtils.createResourceInstance();
- CapabilityData capData = FactoryUtils.createCapabilityData();
-
- FactoryUtils.addComponentInstanceToVF(vf, ri);
- Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> capDataList = prepareCompOperationReturnValue(ri, capData);
-
- prepareMocksForCapabilitiesMethods(ri, capDataList);
-
- Map<String, List<CapabilityDefinition>> capabilities = compOperation.getCapabilities(vf, NodeTypeEnum.Resource, false).left().value();
- assertTrue(capabilities.size() == 1);
- Entry<String, List<CapabilityDefinition>> entry = capabilities.entrySet().iterator().next();
- assertTrue(entry.getKey().equals(capData.getType()));
- assertTrue(entry.getValue().size() == 1);
- assertTrue(entry.getValue().get(0).getUniqueId().equals(capData.getUniqueId()));
- }
-
- @Test
- public void testGetRequirments() {
- Resource vf = FactoryUtils.createVF();
- ComponentInstance ri = FactoryUtils.createResourceInstance();
-
- RequirementData reqData = FactoryUtils.createRequirementData();
-
- FactoryUtils.addComponentInstanceToVF(vf, ri);
-
- Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> reqDataEdgeList = prepareCompOperationReturnValue(ri, reqData);
-
- prepareMocksForRequirmenetsMethods(ri, reqDataEdgeList);
-
- Map<String, List<RequirementDefinition>> requirements = compOperation.getRequirements(vf, NodeTypeEnum.Resource, false).left().value();
- assertTrue(requirements.size() == 1);
- Entry<String, List<RequirementDefinition>> entry = requirements.entrySet().iterator().next();
- assertTrue(entry.getKey().equals(FactoryUtils.Constants.DEFAULT_CAPABILITY_TYPE));
- assertTrue(entry.getValue().size() == 1);
- assertTrue(entry.getValue().get(0).getUniqueId().equals(reqData.getUniqueId()));
- }
-
- private void prepareMocksForRequirmenetsMethods(ComponentInstance ri, Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> reqDataEdgeList) {
-
- when(componentInstanceOperation.getRequirements(ri, NodeTypeEnum.Resource)).thenReturn(reqDataEdgeList);
- when(requirementOperation.getRequirement(Mockito.anyString())).then(createReqDefAnswer());
- }
-
- private void prepareMocksForCapabilitiesMethods(ComponentInstance ri, Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> capDataList) {
- when(componentInstanceOperation.getCapabilities(ri, NodeTypeEnum.Resource)).thenReturn(capDataList);
- when(capabilityOperation.getCapabilityByCapabilityData(Mockito.any(CapabilityData.class))).then(createCapDefByDataAnswer());
- List<ImmutablePair<CapabilityInstData, GraphEdge>> capInstList = new ArrayList<>();
- CapabilityInstData curCapabilityInst = FactoryUtils.createCapabilityInstData();
- GraphEdge edge = new GraphEdge();
- Map<String, Object> properties = new HashMap<>();
- properties.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capDataList.left().value().get(0).getLeft().getUniqueId());
- edge.setProperties(properties);
- ImmutablePair<CapabilityInstData, GraphEdge> pair = new ImmutablePair<CapabilityInstData, GraphEdge>(curCapabilityInst, edge);
- capInstList.add(pair);
- when(titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByNameIgnoreCase(ri.getOriginType().getInstanceType().trim())), ri.getUniqueId(), GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst,
- CapabilityInstData.class)).thenReturn(Either.left(capInstList));
-
- when(titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curCapabilityInst.getLabel())), curCapabilityInst.getUniqueId(), GraphEdgeLabels.INSTANCE_OF, NodeTypeEnum.Capability, CapabilityData.class))
- .thenReturn(Either.left(capDataList.left().value().get(0)));
-
- PropertyValueData propertyValueData = FactoryUtils.createPropertyData();
- ImmutablePair<PropertyValueData, GraphEdge> propPair = new ImmutablePair<PropertyValueData, GraphEdge>(propertyValueData, null);
- List<ImmutablePair<PropertyValueData, GraphEdge>> propPairList = new ArrayList<>();
- propPairList.add(propPair);
- when(titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curCapabilityInst.getLabel())), curCapabilityInst.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue,
- PropertyValueData.class)).thenReturn(Either.left(propPairList));
-
- CapabilityDefinition capDef = FactoryUtils.convertCapabilityDataToCapabilityDefinitionAddProperties(capDataList.left().value().get(0).getLeft());
- List<PropertyDefinition> propDefList = capDef.getProperties().stream().filter(p -> p.getName().equals("host")).collect(Collectors.toList());
- PropertyDefinition propDef = propDefList.get(0);
- PropertyData propData = FactoryUtils.convertCapabilityDefinitionToCapabilityData(propDef);
-
- ImmutablePair<PropertyData, GraphEdge> defPropPair = new ImmutablePair<PropertyData, GraphEdge>(propData, edge);
-
- when(titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(propertyValueData.getLabel())), propertyValueData.getUniqueId(), GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class))
- .thenReturn(Either.left(defPropPair));
- List<CapabilityDefinition> capDefList = new ArrayList<>();
- capDefList.add(capDef);
- when(componentInstanceOperation.updateCapDefPropertyValues(Mockito.any(ComponentInstance.class), Mockito.any(List.class))).thenReturn(Either.left(capDefList));
- }
-
- private <Data> Either<List<ImmutablePair<Data, GraphEdge>>, TitanOperationStatus> prepareCompOperationReturnValue(ComponentInstance ri, Data data) {
- ImmutablePair<Data, GraphEdge> dataEdgePair = new ImmutablePair<>(data, new GraphEdge());
- List<ImmutablePair<Data, GraphEdge>> dataEdgeList = new ArrayList<>();
- dataEdgeList.add(dataEdgePair);
- return Either.left(dataEdgeList);
- }
-
- private Answer<Either<RequirementDefinition, TitanOperationStatus>> createReqDefAnswer() {
- return new Answer<Either<RequirementDefinition, TitanOperationStatus>>() {
-
- @Override
- public Either<RequirementDefinition, TitanOperationStatus> answer(InvocationOnMock invocation) throws Throwable {
- String reqDataId = (String) invocation.getArguments()[0];
- return Either.left(FactoryUtils.convertRequirementDataIDToRequirementDefinition(reqDataId));
- }
- };
- }
-
- private Answer<Either<CapabilityDefinition, TitanOperationStatus>> createCapDefByDataAnswer() {
- return new Answer<Either<CapabilityDefinition, TitanOperationStatus>>() {
-
- @Override
- public Either<CapabilityDefinition, TitanOperationStatus> answer(InvocationOnMock invocation) throws Throwable {
- CapabilityData capData = (CapabilityData) invocation.getArguments()[0];
- return Either.left(FactoryUtils.convertCapabilityDataToCapabilityDefinitionAddProperties(capData));
- }
- };
- }
-
- private ComponentOperation getAnnonimusImpl() {
- return new ComponentOperation() {
-
- @Override
- protected StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected <T extends Component> StorageOperationStatus updateDerived(Component component, Component currentComponent, ComponentMetadataData updatedResourceData, Class<T> clazz) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected <T> Either<T, StorageOperationStatus> updateComponent(T component, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected ComponentMetadataData getMetaDataFromComponent(Component component) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public <T> Either<T, StorageOperationStatus> getLightComponent(String id, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public <T> Either<T, StorageOperationStatus> getComponent(String id, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- // @Override
- // public <T> Either<T, StorageOperationStatus>
- // getComponent_tx(String id, boolean inTransaction) {
- // // TODO Auto-generated method stub
- // return null;
- // }
-
- @Override
- public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Component getDefaultComponent() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean isComponentExist(String componentId) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public Either<Component, StorageOperationStatus> getMetadataComponent(String id, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- Component convertComponentMetadataDataToComponent(ComponentMetadataData componentMetadataData) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- TitanOperationStatus setComponentCategoriesFromGraph(Component component) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String componentName) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<Component, StorageOperationStatus> deleteComponent(String id, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTrasnaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTransaction) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterParametersView) {
- // TODO Auto-generated method stub
- return null;
- }
-
- };
- }
-
-}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java
index 759fd2b811..d1389f0f94 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/InterfaceOperationTest.java
@@ -20,45 +20,27 @@
package org.openecomp.sdc.be.model.operations.impl;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.HashMap;
-import java.util.Map;
-
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.ModelTestBase;
import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.be.resources.data.UserData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-import fj.data.Either;
+import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-context-test.xml")
@@ -78,9 +60,6 @@ public class InterfaceOperationTest {
@javax.annotation.Resource(name = "interface-operation")
private InterfaceLifecycleOperation interfaceOperation;
- @javax.annotation.Resource(name = "resource-operation")
- private ResourceOperation resourceOperation;
-
@javax.annotation.Resource(name = "property-operation")
private PropertyOperation propertyOperation;
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java
deleted file mode 100644
index 23090fe143..0000000000
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperationTest.java
+++ /dev/null
@@ -1,1993 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TestName;
-import org.junit.runner.RunWith;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.InterfaceDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.ModelTestBase;
-import org.openecomp.sdc.be.model.Operation;
-import org.openecomp.sdc.be.model.PropertyConstraint;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil;
-import org.openecomp.sdc.be.model.operations.impl.util.ResourceCreationUtils;
-import org.openecomp.sdc.be.model.tosca.ToscaType;
-import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint;
-import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint;
-import org.openecomp.sdc.be.resources.data.CapabilityData;
-import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
-import org.openecomp.sdc.be.resources.data.InterfaceData;
-import org.openecomp.sdc.be.resources.data.OperationData;
-import org.openecomp.sdc.be.resources.data.RequirementData;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
-import org.openecomp.sdc.be.resources.data.UserData;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.thinkaurelius.titan.core.TitanGraph;
-//import com.tinkerpop.blueprints.Vertex;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration("classpath:application-context-test.xml")
-public class LifecycleOperationTest extends ModelTestBase {
- private static Logger log = LoggerFactory.getLogger(LifecycleOperationTest.class.getName());
- private static final String CAPABILITY_HOSTED_ON = "HostedOn";
-
- private static final String INTERFACE_OPERATION_CREATE = "create";
-
- private static final String INTERFACE_NAME = "standard";
-
- private static final String CATEGORY_NAME = "category/mycategory";
-
- private static final String SERVICE_NAME = "myService";
-
- private static final String REQUIREMENT_NAME = "requirementName";
-
- private static final String CAPABILITY_NAME = "capName";
-
- private static final String USER_ID = "muUserId";
-
- @javax.annotation.Resource
- private TitanGenericDao titanGenericDao;
-
- @javax.annotation.Resource
- private ResourceOperation resourceOperation;
-
- @javax.annotation.Resource
- private ServiceOperation serviceOperation;
-
- @javax.annotation.Resource
- private LifecycleOperation lifecycleOperation;
-
- @javax.annotation.Resource
- private CapabilityTypeOperation capabilityTypeOperation;
-
- @javax.annotation.Resource
- private ArtifactOperation artifactOperation;
-
- @javax.annotation.Resource
- private InterfaceLifecycleOperation interfaceOperation;
-
- @javax.annotation.Resource(name = "property-operation")
- private PropertyOperation propertyOperation;
-
- @javax.annotation.Resource(name = "capability-operation")
- private CapabilityOperation capabilityOperation;
-
- @javax.annotation.Resource(name = "component-instance-operation")
- private ComponentInstanceOperation resourceInstanceOperation;
-
- @javax.annotation.Resource(name = "requirement-operation")
- private RequirementOperation requirementOperation;
-
- User checkoutUser;
- User checkinUser;
- User rfcUser;
- User testerUser;
- User adminUser;
-
- @Rule
- public TestName name = new TestName();
-
- @BeforeClass
- public static void initLifecycleOperation() {
- ModelTestBase.init();
- // new ConfigurationSource() {
- //
- // @Override
- // public <T> T getAndWatchConfiguration(Class<T> className,
- // ConfigurationListener configurationListener) {
- // // TODO Auto-generated method stub
- // return null;
- // }
- //
- // @Override
- // public <T> void addWatchConfiguration(Class<T> className,
- // ConfigurationListener configurationListener) {
- // // TODO Auto-generated method stub
- //
- // }
- // });
- //
-
- }
-
- @Before
- public void setupBefore() {
- clearGraph();
- UserData modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "co", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
- checkoutUser = convertUserDataToUser(modifierData);
-
- modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "ci", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
- checkinUser = convertUserDataToUser(modifierData);
-
- modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "rfc", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
- rfcUser = convertUserDataToUser(modifierData);
-
- modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "tester", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "TESTER");
- testerUser = convertUserDataToUser(modifierData);
-
- modifierData = deleteAndCreateUser(ResourceCreationUtils.MODIFIER_ATT_UID + "admin", ResourceCreationUtils.MODIFIER_FIRST_NAME, ResourceCreationUtils.MODIFIER_LAST_NAME, "ADMIN");
- adminUser = convertUserDataToUser(modifierData);
-
- modifierData = deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID, "ADMIN");
- adminUser = convertUserDataToUser(modifierData);
-
- String[] category = CATEGORY_NAME.split("/");
- OperationTestsUtil.deleteAndCreateServiceCategory(CATEGORY_NAME, titanGenericDao);
- OperationTestsUtil.deleteAndCreateResourceCategory(category[0], category[1], titanGenericDao);
-
- }
-
- @After
- public void teardown() {
- clearGraph();
- }
-
- private void clearGraph() {
- Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph();
- TitanGraph graph = graphResult.left().value();
-
- Iterable<TitanVertex> vertices = graph.query().vertices();
- if (vertices != null) {
- Iterator<TitanVertex> iterator = vertices.iterator();
- while (iterator.hasNext()) {
- TitanVertex vertex = iterator.next();
- // graph.removeVertex(vertex);
- vertex.remove();
- }
-
- }
- titanGenericDao.commit();
- }
-
- @Test
- @Ignore
- public void getOwnerTest() {
-
- Resource resultResource = createTestResource(checkoutUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
- assertEquals("check modifier", checkoutUser.getUserId(), resourceOwner.getUserId());
-
- }
-
- /*********************** CHECKOUT ***************************************************************/
-
- @Test
- @Ignore
- public void checkoutCertifiedTest() {
-
- Resource resultResource = createTestResource(adminUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null);
- String origUniqueId = resultResource.getUniqueId();
- Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource(origUniqueId);
- Resource origResource = origResourceResult.left().value();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- // checkout
- Either<Resource, StorageOperationStatus> checkoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, checkoutResponse.isLeft());
- Resource checkoutResource = checkoutResponse.left().value();
-
- assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- assertEquals(checkoutResource.getVersion(), "1.1");
- assertEquals(checkoutResource.getCreatorUserId(), adminUser.getUserId());
- assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId());
-
- // assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false);
- assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
- resourceOwner = getOwnerCheckoutResponse.left().value();
- assertTrue(resourceOwner.equals(checkoutUser));
-
- // assert original resource not deleted
- Either<Resource, StorageOperationStatus> getOrigResource = resourceOperation.getResource(origUniqueId);
- assertEquals("check resource created", true, getOrigResource.isLeft());
- // assertEquals("assert original resource not changed", origResource,
- // getOrigResource.left().value());
- }
-
- @Test
- @Ignore
- public void checkoutDefaultTest() {
-
- Resource resultResource = createTestResource(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
- String origUniqueId = resultResource.getUniqueId();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- // checkout
- Either<Resource, StorageOperationStatus> checkoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, checkoutResponse.isLeft());
- Resource checkoutResource = checkoutResponse.left().value();
-
- assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- assertEquals(checkoutResource.getVersion(), "0.2");
- assertEquals(checkoutResource.getCreatorUserId(), checkinUser.getUserId());
- assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId());
- assertEquals(checkoutResource.isHighestVersion(), true);
-
- // assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false);
- assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
- resourceOwner = getOwnerCheckoutResponse.left().value();
- assertTrue(resourceOwner.equals(checkoutUser));
-
- // assert original resource not deleted
- Either<Resource, StorageOperationStatus> getOrigResource = resourceOperation.getResource(origUniqueId);
- assertEquals("check resource created", true, getOrigResource.isLeft());
- // assertEquals("assert original resource not changed", origResource,
- // getOrigResource.left().value());
- assertEquals("assert original resource not highest version", false, getOrigResource.left().value().isHighestVersion());
- }
-
- @Test
- @Ignore
- public void checkoutFullResourceTest() {
-
- Resource origResource = createFullTestResource(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- String origUniqueId = origResource.getUniqueId();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- // checkout
- Either<Resource, StorageOperationStatus> checkoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, origResource, checkoutUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, checkoutResponse.isLeft());
- Resource checkoutResource = checkoutResponse.left().value();
-
- assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- assertEquals(checkoutResource.getVersion(), "0.2");
- assertEquals(checkoutResource.getCreatorUserId(), checkinUser.getUserId());
- assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId());
- assertEquals(checkoutResource.isHighestVersion(), true);
-
- assertNotNull(checkoutResource.getArtifacts());
- assertFalse(checkoutResource.getArtifacts().isEmpty());
- assertNotNull(checkoutResource.getInterfaces());
- assertFalse(checkoutResource.getInterfaces().isEmpty());
- Map<String, InterfaceDefinition> interfaces = checkoutResource.getInterfaces();
- assertTrue(interfaces.containsKey(INTERFACE_NAME));
- InterfaceDefinition interfaceDef = interfaces.get(INTERFACE_NAME);
- Map<String, Operation> operations = interfaceDef.getOperationsMap();
- assertNotNull(operations);
- assertFalse(operations.isEmpty());
- assertTrue(operations.containsKey(INTERFACE_OPERATION_CREATE));
- Operation op = operations.get(INTERFACE_OPERATION_CREATE);
- assertNotNull(op.getImplementation());
-
- // assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Resource, false);
- assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
- resourceOwner = getOwnerCheckoutResponse.left().value();
- assertTrue(resourceOwner.equals(checkoutUser));
-
- // assert original resource not deleted
- Either<Resource, StorageOperationStatus> getOrigResource = resourceOperation.getResource(origUniqueId);
- assertEquals("check resource created", true, getOrigResource.isLeft());
- // assertEquals("assert original resource not changed", origResource,
- // getOrigResource.left().value());
- assertEquals("assert original resource not highest version", false, getOrigResource.left().value().isHighestVersion());
- }
-
- @Test
- @Ignore
- public void getResourceOwnerResourceNotExistTest() {
-
- // create resource metadata
- Resource resource = buildResourceMetadata(adminUser.getUserId(), CATEGORY_NAME);
- resource.setLifecycleState(LifecycleStateEnum.CERTIFIED);
- resource.setUniqueId("my-resource.0.1");
-
- Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource("my-resource.0.1");
- assertEquals("assert resource not exist", true, origResourceResult.isRight());
-
- // get resource owner
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner("my-resource.0.1", NodeTypeEnum.Resource, false);
-
- assertEquals("assert no owner", true, getOwnerResponse.isRight());
- StorageOperationStatus status = getOwnerResponse.right().value();
-
- assertEquals(StorageOperationStatus.INVALID_ID, status);
-
- }
-
- @Test
- @Ignore
- public void checkoutResourceTwice() {
-
- Resource resultResource = createTestResource(adminUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null);
- String origUniqueId = resultResource.getUniqueId();
- Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource(origUniqueId);
- Resource origResource = origResourceResult.left().value();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- // first checkout
- Either<Resource, StorageOperationStatus> checkoutResponse1 = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, checkoutResponse1.isLeft());
-
- // second checkout
- Either<Resource, StorageOperationStatus> checkoutResponse2 = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, origResource, checkoutUser, resourceOwner, false);
- assertEquals("check checkout failed", true, checkoutResponse2.isRight());
- assertEquals(StorageOperationStatus.ENTITY_ALREADY_EXISTS, checkoutResponse2.right().value());
-
- }
-
- /******** SERVICE */
- @Test
- public void checkoutServiceDefaultTest() {
-
- Service resultResource = createTestService(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
- String origUniqueId = resultResource.getUniqueId();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- // checkout
- Either<? extends Component, StorageOperationStatus> checkoutResponse = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, checkoutResponse.isLeft());
- Component checkoutResource = checkoutResponse.left().value();
-
- assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- assertEquals(checkoutResource.getVersion(), "0.2");
- assertEquals(checkoutResource.getCreatorUserId(), checkinUser.getUserId());
- assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId());
- assertEquals(checkoutResource.isHighestVersion(), true);
-
- // assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Service, false);
- assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
- resourceOwner = getOwnerCheckoutResponse.left().value();
- assertTrue(resourceOwner.equals(checkoutUser));
-
- // assert original resource not deleted
- Either<Service, StorageOperationStatus> getOrigResource = serviceOperation.getService(origUniqueId);
- assertEquals("check resource created", true, getOrigResource.isLeft());
- // assertEquals("assert original resource not changed", origResource,
- // getOrigResource.left().value());
- assertEquals("assert original resource not highest version", false, getOrigResource.left().value().isHighestVersion());
- }
-
- @Test
- @Ignore
- public void checkoutFullServiceTest() {
-
- Service origService = createTestService(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
- String origUniqueId = origService.getUniqueId();
-
- // add artifacts
- addArtifactToService(checkinUser.getUserId(), origService.getUniqueId(), "install_apache");
- addArtifactToService(checkinUser.getUserId(), origService.getUniqueId(), "start_apache");
-
- // add resource instances
- ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest();
- riTest.setOperations(titanGenericDao, capabilityTypeOperation, requirementOperation, capabilityOperation, resourceOperation, propertyOperation, resourceInstanceOperation);
- riTest.addResourceInstancesAndRelation(origService.getUniqueId());
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- Either<Service, StorageOperationStatus> serviceBeforeCheckout = serviceOperation.getService(origUniqueId, true);
- assertTrue(serviceBeforeCheckout.isLeft());
- origService = serviceBeforeCheckout.left().value();
-
- // checkout
- Either<? extends Component, StorageOperationStatus> checkoutResponse = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, origService, checkoutUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, checkoutResponse.isLeft());
- Service checkoutResource = (Service) checkoutResponse.left().value();
-
- assertEquals(checkoutResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- assertEquals(checkoutResource.getVersion(), "0.2");
- assertEquals(checkoutResource.getCreatorUserId(), checkinUser.getUserId());
- assertEquals(checkoutResource.getLastUpdaterUserId(), checkoutUser.getUserId());
- assertEquals(checkoutResource.isHighestVersion(), true);
-
- assertNotNull(checkoutResource.getArtifacts());
- assertFalse(checkoutResource.getArtifacts().isEmpty());
- assertNotNull(checkoutResource.getComponentInstances());
- assertFalse(checkoutResource.getComponentInstances().isEmpty());
- assertNotNull(checkoutResource.getComponentInstancesRelations());
- assertFalse(checkoutResource.getComponentInstancesRelations().isEmpty());
-
- // assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkoutResource.getUniqueId(), NodeTypeEnum.Service, false);
- assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
- resourceOwner = getOwnerCheckoutResponse.left().value();
- assertTrue(resourceOwner.equals(checkoutUser));
-
- // assert original resource not deleted
- Either<Service, StorageOperationStatus> getOrigResource = serviceOperation.getService(origUniqueId);
- assertEquals("check service created", true, getOrigResource.isLeft());
- // assertEquals("assert original resource not changed", origResource,
- // getOrigResource.left().value());
- assertEquals("assert original service not highest version", false, getOrigResource.left().value().isHighestVersion());
- }
-
- @Test
- @Ignore
- public void checkoutServiceTwice() {
-
- Service resultResource = createTestService(adminUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null);
- String origUniqueId = resultResource.getUniqueId();
- Either<Service, StorageOperationStatus> origResourceResult = serviceOperation.getService(origUniqueId);
- Service origResource = origResourceResult.left().value();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- // first checkout
- Either<? extends Component, StorageOperationStatus> checkoutResponse1 = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, checkoutResponse1.isLeft());
-
- // second checkout
- Either<? extends Component, StorageOperationStatus> checkoutResponse2 = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, origResource, checkoutUser, resourceOwner, false);
- assertEquals("check checkout failed", true, checkoutResponse2.isRight());
- assertEquals(StorageOperationStatus.ENTITY_ALREADY_EXISTS, checkoutResponse2.right().value());
-
- }
-
- /**************************** CHECKIN ********************************************************************/
-
- @Test
- @Ignore
- public void checkinDefaultTest() {
-
- Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
- String origUniqueId = resultResource.getUniqueId();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- // checkin
- Either<Resource, StorageOperationStatus> checkinResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkinComponent(NodeTypeEnum.Resource, resultResource, checkinUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, checkinResponse.isLeft());
- Resource checkinResource = checkinResponse.left().value();
-
- assertEquals(checkinResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- assertEquals(checkinResource.getVersion(), "0.1");
- assertEquals(checkinResource.getCreatorUserId(), adminUser.getUserId());
- assertEquals(checkinResource.getLastUpdaterUserId(), checkinUser.getUserId());
-
- // assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkinResource.getUniqueId(), NodeTypeEnum.Resource, false);
- assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
- resourceOwner = getOwnerCheckoutResponse.left().value();
- assertTrue(resourceOwner.equals(checkinUser));
-
- }
-
- @Test
- @Ignore
- public void checkinFromRfcTest() {
-
- Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
- String origUniqueId = resultResource.getUniqueId();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- // checkin
- Either<Resource, StorageOperationStatus> checkinResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkinComponent(NodeTypeEnum.Resource, resultResource, checkinUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, checkinResponse.isLeft());
-
- // rfc
- Either<Resource, StorageOperationStatus> rfcResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, checkinResponse.left().value(), rfcUser, checkinUser, false);
- assertEquals("check resource object is returned", true, checkinResponse.isLeft());
-
- // checkin (cancel rfc)
- checkinResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkinComponent(NodeTypeEnum.Resource, rfcResponse.left().value(), checkinUser, rfcUser, false);
- assertEquals("check resource object is returned", true, checkinResponse.isLeft());
- resultResource = checkinResponse.left().value();
-
- assertEquals(resultResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- assertEquals(resultResource.getVersion(), "0.1");
- assertEquals(resultResource.getCreatorUserId(), adminUser.getUserId());
- assertEquals(resultResource.getLastUpdaterUserId(), checkinUser.getUserId());
-
- // assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false);
- assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
- resourceOwner = getOwnerCheckoutResponse.left().value();
- assertTrue(resourceOwner.equals(checkinUser));
-
- // assert relations
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(resultResource.getUniqueId());
- Map<String, Object> props = new HashMap<String, Object>();
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isRight());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- }
-
- /*** SERVICE */
- @Test
- @Ignore
- public void checkinServiceDefaultTest() {
-
- Service resultService = createTestService(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
- String origUniqueId = resultService.getUniqueId();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- // checkin
- Either<? extends Component, StorageOperationStatus> checkinResponse = lifecycleOperation.checkinComponent(NodeTypeEnum.Service, resultService, checkinUser, resourceOwner, false);
- assertEquals("check service object is returned", true, checkinResponse.isLeft());
- Service checkinResource = (Service) checkinResponse.left().value();
-
- assertEquals(checkinResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- assertEquals(checkinResource.getVersion(), "0.1");
- assertEquals(checkinResource.getCreatorUserId(), adminUser.getUserId());
- assertEquals(checkinResource.getLastUpdaterUserId(), checkinUser.getUserId());
-
- // assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(checkinResource.getUniqueId(), NodeTypeEnum.Service, false);
- assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
- resourceOwner = getOwnerCheckoutResponse.left().value();
- assertTrue(resourceOwner.equals(checkinUser));
-
- }
-
- @Test
- @Ignore
- public void checkinServiceFromRfcTest() {
-
- Service resultResource = createTestService(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
- String origUniqueId = resultResource.getUniqueId();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- // checkin
- Either<? extends Component, StorageOperationStatus> checkinResponse = lifecycleOperation.checkinComponent(NodeTypeEnum.Service, resultResource, checkinUser, resourceOwner, false);
- assertEquals("check service object is returned", true, checkinResponse.isLeft());
-
- // rfc
- Either<? extends Component, StorageOperationStatus> rfcResponse = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, checkinResponse.left().value(), rfcUser, checkinUser, false);
- assertEquals("check service object is returned", true, checkinResponse.isLeft());
-
- // checkin (cancel rfc)
- checkinResponse = lifecycleOperation.checkinComponent(NodeTypeEnum.Service, rfcResponse.left().value(), checkinUser, rfcUser, false);
- assertEquals("check resource object is returned", true, checkinResponse.isLeft());
- resultResource = (Service) checkinResponse.left().value();
-
- assertEquals(resultResource.getLifecycleState(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- assertEquals(resultResource.getVersion(), "0.1");
- assertEquals(resultResource.getCreatorUserId(), adminUser.getUserId());
- assertEquals(resultResource.getLastUpdaterUserId(), checkinUser.getUserId());
-
- // assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Service, false);
- assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
- resourceOwner = getOwnerCheckoutResponse.left().value();
- assertTrue(resourceOwner.equals(checkinUser));
-
- // assert relations
- ServiceMetadataDataDefinition metadata = new ServiceMetadataDataDefinition();
- metadata.setUniqueId(resultResource.getUniqueId());
- ServiceMetadataData resourceData = new ServiceMetadataData(metadata);
- Map<String, Object> props = new HashMap<String, Object>();
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isRight());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- }
-
- /****************************
- * UNDO CHECKOUT
- ********************************************************************/
-
- @Test
- @Ignore
- public void undoCheckoutNewResourceTest() {
-
- Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
- String origUniqueId = resultResource.getUniqueId();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- //
-
- // undo checkout
- Either<Resource, StorageOperationStatus> undoCheckoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.undoCheckout(NodeTypeEnum.Resource, resultResource, adminUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft());
-
- Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource(origUniqueId);
- assertTrue(origResourceResult.isRight());
- /*
- * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true);
- */
- }
-
- @Test
- @Ignore
- public void undoCheckoutNewFullResourceTest() {
-
- Resource resultResource = createFullTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- String origUniqueId = resultResource.getUniqueId();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- // undo checkout
- Either<Resource, StorageOperationStatus> undoCheckoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.undoCheckout(NodeTypeEnum.Resource, resultResource, adminUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft());
-
- Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource(origUniqueId);
- /*
- * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true);
- */ assertTrue(origResourceResult.isRight());
-
- String interfaceId = origUniqueId + "." + INTERFACE_NAME;
- Either<InterfaceData, TitanOperationStatus> node = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceId, InterfaceData.class);
- assertTrue(node.isRight());
-
- String operationId = interfaceId + "." + INTERFACE_OPERATION_CREATE;
- Either<OperationData, TitanOperationStatus> op = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InterfaceOperation), operationId, OperationData.class);
- assertTrue(op.isRight());
-
- String capabilityId = "capability." + origUniqueId + "." + CAPABILITY_NAME;
- Either<CapabilityData, TitanOperationStatus> capability = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityId, CapabilityData.class);
- assertTrue(capability.isRight());
-
- String requirementId = origUniqueId + "." + REQUIREMENT_NAME;
- Either<RequirementData, TitanOperationStatus> req = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementId, RequirementData.class);
- assertTrue(req.isRight());
-
- }
-
- @Test
- @Ignore
- public void undoCheckoutExistingResourceTest() {
-
- Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
-
- // get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- String prevResourceId = resultResource.getUniqueId();
- Either<Resource, StorageOperationStatus> result2 = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, resultResource, checkoutUser, resourceOwner, false);
- assertEquals("check resource created", true, result2.isLeft());
- Resource resultResource2 = result2.left().value();
-
- // get resource owner
- getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource2.getUniqueId(), NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- resourceOwner = getOwnerResponse.left().value();
- assertEquals(resourceOwner, checkoutUser);
-
- // undo checkout
- Either<Resource, StorageOperationStatus> undoCheckoutResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.undoCheckout(NodeTypeEnum.Resource, resultResource2, checkoutUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft());
-
- // get previous resource
- Either<Resource, StorageOperationStatus> resourceAfterUndo = resourceOperation.getResource(prevResourceId);
- assertTrue(resourceAfterUndo.isLeft());
- Resource actualResource = resourceAfterUndo.left().value();
- assertTrue(actualResource.isHighestVersion());
- assertEquals(adminUser.getUserId(), actualResource.getCreatorUserId());
- assertEquals(adminUser.getUserId(), actualResource.getLastUpdaterUserId());
- assertEquals("0.1", actualResource.getVersion());
- assertEquals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, actualResource.getLifecycleState());
-
- Either<Resource, StorageOperationStatus> origResourceResult = resourceOperation.getResource(resultResource2.getUniqueId());
- /*
- * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true);
- */ assertTrue(origResourceResult.isRight());
-
- }
-
- /**** SERVICE ***/
- @Test
- @Ignore
- public void undoCheckoutNewServiceTest() {
-
- Service resultResource = createTestService(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null);
- String origUniqueId = resultResource.getUniqueId();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- //
-
- // undo checkout
- Either<? extends Component, StorageOperationStatus> undoCheckoutResponse = lifecycleOperation.undoCheckout(NodeTypeEnum.Service, resultResource, adminUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft());
-
- Either<Service, StorageOperationStatus> origResourceResult = serviceOperation.getService(origUniqueId);
- /*
- * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true);
- */ assertTrue(origResourceResult.isRight());
-
- }
-
- @Test
- @Ignore
- public void undoCheckoutNewFullServiceTest() {
-
- Service origService = createTestService(checkinUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
- String origUniqueId = origService.getUniqueId();
-
- // add artifacts
- addArtifactToService(checkinUser.getUserId(), origService.getUniqueId(), "install_apache");
- addArtifactToService(checkinUser.getUserId(), origService.getUniqueId(), "start_apache");
-
- // add resource instances
- ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest();
- riTest.setOperations(titanGenericDao, capabilityTypeOperation, requirementOperation, capabilityOperation, resourceOperation, propertyOperation, resourceInstanceOperation);
- riTest.addResourceInstancesAndRelation(origService.getUniqueId());
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- Either<Service, StorageOperationStatus> service = serviceOperation.getService(origUniqueId);
- assertTrue(service.isLeft());
-
- Service resultResource = service.left().value();
- List<ComponentInstance> resourceInstances = resultResource.getComponentInstances();
-
- // undo checkout
- Either<? extends Component, StorageOperationStatus> undoCheckoutResponse = lifecycleOperation.undoCheckout(NodeTypeEnum.Service, resultResource, adminUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft());
-
- Either<Service, StorageOperationStatus> origResourceResult = serviceOperation.getService(origUniqueId);
- /*
- * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true);
- */ assertTrue(origResourceResult.isRight());
-
- for (ComponentInstance ri : resourceInstances) {
- Either<ComponentInstanceData, TitanOperationStatus> node = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), ri.getUniqueId(), ComponentInstanceData.class);
- assertTrue(node.isRight());
- }
-
- }
-
- @Test
- @Ignore
- public void undoCheckoutExistingServiceTest() {
-
- Service resultResource = createTestService(adminUser.getUserId(), "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
-
- // get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource.getUniqueId(), NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- String prevResourceId = resultResource.getUniqueId();
- Either<? extends Component, StorageOperationStatus> result2 = lifecycleOperation.checkoutComponent(NodeTypeEnum.Service, resultResource, checkoutUser, resourceOwner, false);
- assertEquals("check resource created", true, result2.isLeft());
- Component resultResource2 = result2.left().value();
- String result2Uid = resultResource.getUniqueId();
-
- // get resource owner
- getOwnerResponse = lifecycleOperation.getComponentOwner(resultResource2.getUniqueId(), NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- resourceOwner = getOwnerResponse.left().value();
- assertEquals(resourceOwner, checkoutUser);
-
- // undo checkout
- Either<? extends Component, StorageOperationStatus> undoCheckoutResponse = lifecycleOperation.undoCheckout(NodeTypeEnum.Service, resultResource2, checkoutUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, undoCheckoutResponse.isLeft());
-
- // get previous resource
- Either<Service, StorageOperationStatus> resourceAfterUndo = serviceOperation.getService(prevResourceId);
- assertTrue(resourceAfterUndo.isLeft());
- Service actualResource = resourceAfterUndo.left().value();
- assertTrue(actualResource.isHighestVersion());
- assertEquals(adminUser.getUserId(), actualResource.getCreatorUserId());
- assertEquals(adminUser.getUserId(), actualResource.getLastUpdaterUserId());
- assertEquals("0.1", actualResource.getVersion());
- assertEquals(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, actualResource.getLifecycleState());
-
- Either<Service, StorageOperationStatus> origResourceResult = serviceOperation.getService(result2Uid);
- /*
- * assertTrue(origResourceResult.isLeft()); assertTrue(origResourceResult.left().value().getIsDeleted() == true);
- */ assertTrue(origResourceResult.isRight());
-
- }
-
- /****************************
- * CERTIFICATION REQUEST
- ********************************************************************/
-
- @Test
- @Ignore
- public void certReqDefaultTest() {
- Resource actualResource = testCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
-
- // assert relations
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId());
- Map<String, Object> props = new HashMap<String, Object>();
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(adminUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- }
-
- @Test
- @Ignore
- public void atomicCheckinCertReqTest() {
- Resource actualResource = testCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
-
- // assert relations
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId());
- Map<String, Object> props = new HashMap<String, Object>();
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
- }
-
- private Resource testCertificationRequest(LifecycleStateEnum preState) {
-
- Resource resultResource = createTestResource(adminUser.getUserId(), "0.1", preState, null);
- String origUniqueId = resultResource.getUniqueId();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- // checkin
- Either<Resource, StorageOperationStatus> certReqResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, certReqResponse.isLeft());
- Resource resourceAfterChange = certReqResponse.left().value();
-
- assertEquals(resourceAfterChange.getLifecycleState(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- assertEquals(resourceAfterChange.getVersion(), "0.1");
- assertEquals(resourceAfterChange.getCreatorUserId(), adminUser.getUserId());
- assertEquals(resourceAfterChange.getLastUpdaterUserId(), rfcUser.getUserId());
-
- // assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(resourceAfterChange.getUniqueId(), NodeTypeEnum.Resource, false);
- assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
- resourceOwner = getOwnerCheckoutResponse.left().value();
- assertTrue(resourceOwner.equals(rfcUser));
-
- return resourceAfterChange;
- }
-
- /** SERVICE **/
- @Test
- @Ignore
- public void certServiceReqDefaultTest() {
- Service actualResource = testServiceCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
-
- // assert relations
- ServiceMetadataDataDefinition metadata = new ServiceMetadataDataDefinition();
- metadata.setUniqueId(actualResource.getUniqueId());
- ServiceMetadataData serviceData = new ServiceMetadataData(metadata);
- Map<String, Object> props = new HashMap<String, Object>();
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(adminUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- }
-
- @Test
- @Ignore
- public void atomicServiceCheckinCertReqTest() {
- Service actualResource = testServiceCertificationRequest(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
-
- // assert relations
- ServiceMetadataDataDefinition metadata = new ServiceMetadataDataDefinition();
- metadata.setUniqueId(actualResource.getUniqueId());
- ServiceMetadataData serviceData = new ServiceMetadataData(metadata);
- Map<String, Object> props = new HashMap<String, Object>();
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
- }
-
- private Service testServiceCertificationRequest(LifecycleStateEnum preState) {
-
- Service resultResource = createTestService(adminUser.getUserId(), "0.1", preState, null);
- String origUniqueId = resultResource.getUniqueId();
-
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(origUniqueId, NodeTypeEnum.Service, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
-
- // checkin
- Either<? extends Component, StorageOperationStatus> certReqResponse = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultResource, rfcUser, resourceOwner, false);
- assertEquals("check resource object is returned", true, certReqResponse.isLeft());
- Service resourceAfterChange = (Service) certReqResponse.left().value();
-
- assertEquals(resourceAfterChange.getLifecycleState(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- assertEquals(resourceAfterChange.getVersion(), "0.1");
- assertEquals(resourceAfterChange.getCreatorUserId(), adminUser.getUserId());
- assertEquals(resourceAfterChange.getLastUpdaterUserId(), rfcUser.getUserId());
-
- // assert owner changed
- Either<User, StorageOperationStatus> getOwnerCheckoutResponse = lifecycleOperation.getComponentOwner(resourceAfterChange.getUniqueId(), NodeTypeEnum.Service, false);
- assertEquals("check user object is returned", true, getOwnerCheckoutResponse.isLeft());
- resourceOwner = getOwnerCheckoutResponse.left().value();
- assertTrue(resourceOwner.equals(rfcUser));
-
- return resourceAfterChange;
- }
-
- /****************************
- * START CERTIFICATION
- ********************************************************************/
-
- @Test
- @Ignore
- public void startCertificationTest() {
-
- Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
-
- // certification request
- Either<Resource, StorageOperationStatus> requestCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false);
- assertTrue(requestCertificationResult.isLeft());
-
- // start certification
- Either<Resource, StorageOperationStatus> startCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false);
-
- assertEquals(true, startCertificationResult.isLeft());
- Resource actualResource = startCertificationResult.left().value();
-
- // get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
- assertEquals(testerUser.getUserId(), resourceOwner.getUserId());
-
- assertTrue(actualResource.isHighestVersion());
- assertEquals(checkinUser.getUserId(), actualResource.getCreatorUserId());
- assertEquals(testerUser.getUserId(), actualResource.getLastUpdaterUserId());
- assertEquals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, actualResource.getLifecycleState());
-
- // assert relations
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId());
- Map<String, Object> props = new HashMap<String, Object>();
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
- }
-
- /** SERVICE */
- @Test
- @Ignore
- public void startServiceCertificationTest() {
-
- Service resultResource = createTestService(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
-
- // certification request
- Either<? extends Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultResource, rfcUser, checkinUser, false);
- assertTrue(requestCertificationResult.isLeft());
-
- // start certification
- Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultResource, testerUser, rfcUser, false);
-
- assertEquals(true, startCertificationResult.isLeft());
- Service actualResource = (Service) startCertificationResult.left().value();
-
- // get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Service, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
- assertEquals(testerUser.getUserId(), resourceOwner.getUserId());
-
- assertTrue(actualResource.isHighestVersion());
- assertEquals(checkinUser.getUserId(), actualResource.getCreatorUserId());
- assertEquals(testerUser.getUserId(), actualResource.getLastUpdaterUserId());
- assertEquals(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, actualResource.getLifecycleState());
-
- // assert relations
- ServiceMetadataDataDefinition metadata = new ServiceMetadataDataDefinition();
- metadata.setUniqueId(actualResource.getUniqueId());
- ServiceMetadataData serviceData = new ServiceMetadataData(metadata);
- Map<String, Object> props = new HashMap<String, Object>();
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(serviceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
- }
-
- /****************************
- * FAIL CERTIFICATION
- ********************************************************************/
-
- @Test
- @Ignore
- public void failCertificationTest() {
-
- Resource actualResource = certificationStatusChange(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkinUser);
-
- // assert relations
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId());
- Map<String, Object> props = new HashMap<String, Object>();
-
- // old edges removed
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isRight());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isRight());
-
- // new state is checkin
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
- }
-
- /*** SERVICE **/
-
- @Test
- @Ignore
- public void failCertificationServiceTest() {
-
- Service actualService = certificationStatusChangeService(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkinUser);
-
- // assert relations
- ServiceMetadataData resourceData = new ServiceMetadataData((ServiceMetadataDataDefinition) actualService.getComponentMetadataDefinition().getMetadataDataDefinition());
- Map<String, Object> props = new HashMap<String, Object>();
-
- // old edges removed
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isRight());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isRight());
-
- // new state is checkin
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
- }
-
- /****************************
- * CANCEL CERTIFICATION
- ********************************************************************/
-
- @Test
- @Ignore
- public void cancelCertificationTest() {
-
- Resource actualResource = certificationStatusChange(LifecycleStateEnum.READY_FOR_CERTIFICATION, rfcUser);
-
- // assert relations
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId());
- Map<String, Object> props = new HashMap<String, Object>();
-
- // old edges removed
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isRight());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- // new state is rfc
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
- }
-
- /** SERVICE **/
- @Test
- @Ignore
- public void cancelCertificationServiceTest() {
-
- Service actualService = certificationStatusChangeService(LifecycleStateEnum.READY_FOR_CERTIFICATION, rfcUser);
-
- // assert relations
- ServiceMetadataData ServiceNode = new ServiceMetadataData();
- ServiceNode.getMetadataDataDefinition().setUniqueId(actualService.getUniqueId());
- Map<String, Object> props = new HashMap<String, Object>();
-
- // old edges removed
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(ServiceNode, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isRight());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(ServiceNode, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(checkinUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- // new state is rfc
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(ServiceNode, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
- }
-
- /**************************** CERTIFY ********************************************************************/
-
- @Test
- @Ignore
- public void certifyTest() {
-
- Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
-
- // certification request
- Either<Resource, StorageOperationStatus> requestCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false);
- assertTrue(requestCertificationResult.isLeft());
-
- // start certification
- Either<Resource, StorageOperationStatus> startCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false);
- assertEquals(true, startCertificationResult.isLeft());
- Resource actualResource = startCertificationResult.left().value();
-
- // cancel certification
- Either<? extends Component, StorageOperationStatus> CertificationResult = lifecycleOperation.certifyComponent(NodeTypeEnum.Resource, actualResource, testerUser, testerUser, false);
-
- assertEquals(true, CertificationResult.isLeft());
- actualResource = (Resource) CertificationResult.left().value();
-
- // get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
- assertEquals(testerUser.getUserId(), resourceOwner.getUserId());
-
- assertTrue(actualResource.isHighestVersion());
- assertEquals(checkinUser.getUserId(), actualResource.getCreatorUserId());
- assertEquals(testerUser.getUserId(), actualResource.getLastUpdaterUserId());
- assertEquals(LifecycleStateEnum.CERTIFIED, actualResource.getLifecycleState());
-
- // assert relations
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(actualResource.getUniqueId());
- Map<String, Object> props = new HashMap<String, Object>();
-
- // old edges removed
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isRight());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isRight());
-
- // new state is certified
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- }
-
- /******** SERVICE **/
-
- @Test
- @Ignore
- public void certifyServiceTest() {
-
- Service resultService = createTestService(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
-
- // certification request
- Either<? extends Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, rfcUser, checkinUser, false);
- assertTrue(requestCertificationResult.isLeft());
-
- // start certification
- Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService, testerUser, rfcUser, false);
- assertEquals(true, startCertificationResult.isLeft());
- Service actualService = (Service) startCertificationResult.left().value();
-
- // cancel certification
- Either<? extends Component, StorageOperationStatus> CertificationResult = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, actualService, testerUser, testerUser, false);
-
- assertEquals(true, CertificationResult.isLeft());
- actualService = (Service) CertificationResult.left().value();
-
- // get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(actualService.getUniqueId(), NodeTypeEnum.Service, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
- assertEquals(testerUser.getUserId(), resourceOwner.getUserId());
-
- assertTrue(actualService.isHighestVersion());
- assertEquals(checkinUser.getUserId(), actualService.getCreatorUserId());
- assertEquals(testerUser.getUserId(), actualService.getLastUpdaterUserId());
- assertEquals(LifecycleStateEnum.CERTIFIED, actualService.getLifecycleState());
-
- // assert relations
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(actualService.getUniqueId());
- Map<String, Object> props = new HashMap<String, Object>();
-
- // old edges removed
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
- Either<GraphRelation, TitanOperationStatus> incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isRight());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isRight());
-
- // new state is certified
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(testerUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
- incomingRelationByCriteria = titanGenericDao.getIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props);
- assertTrue(incomingRelationByCriteria.isLeft());
- assertEquals(rfcUser.getUserId(), incomingRelationByCriteria.left().value().getFrom().getIdValue());
-
- }
-
- @Test
- @Ignore
- public void testDeleteOldVersionsResource() {
- // simulate
- createTestResource(checkinUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null);
- Resource resourceNewVersion = createTestResource(checkinUser.getUserId(), "1.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
- createTestResource(checkinUser.getUserId(), "1.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, resourceNewVersion.getUUID());
- createTestResource(checkinUser.getUserId(), "1.3", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, resourceNewVersion.getUUID());
- Resource certifiedResource = createTestResource(checkinUser.getUserId(), "2.0", LifecycleStateEnum.CERTIFIED, resourceNewVersion.getUUID());
-
- Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifecycleOperation.deleteOldComponentVersions(NodeTypeEnum.Resource, certifiedResource.getName(), certifiedResource.getUUID(), false);
-
- assertTrue(deleteOldComponentVersions.isLeft());
-
- String resourceName = certifiedResource.getName();
- Either<List<Resource>, StorageOperationStatus> resource = resourceOperation.getResourceByNameAndVersion(resourceName, "1.0", false);
- assertTrue(resource.isLeft());
-
- resource = resourceOperation.getResourceByNameAndVersion(resourceName, "2.0", false);
- assertTrue(resource.isLeft());
-
- resource = resourceOperation.getResourceByNameAndVersion(resourceName, "1.1", false);
- assertTrue(resource.isLeft());
- assertTrue(resource.left().value().size() == 1);
- Resource deleted = resource.left().value().get(0);
- assertTrue(deleted.getIsDeleted());
- // assertEquals(StorageOperationStatus.NOT_FOUND,
- // resource.right().value());
-
- resource = resourceOperation.getResourceByNameAndVersion(resourceName, "1.2", false);
- // assertTrue(resource.isRight());
- // assertEquals(StorageOperationStatus.NOT_FOUND,
- // resource.right().value());
- assertTrue(resource.isLeft());
- assertTrue(resource.left().value().size() == 1);
- deleted = resource.left().value().get(0);
- assertTrue(deleted.getIsDeleted());
-
- resource = resourceOperation.getResourceByNameAndVersion(resourceName, "1.3", false);
- // assertTrue(resource.isRight());
- // assertEquals(StorageOperationStatus.NOT_FOUND,
- // resource.right().value());
- assertTrue(resource.isLeft());
- assertTrue(resource.left().value().size() == 1);
- deleted = resource.left().value().get(0);
- assertTrue(deleted.getIsDeleted());
- }
-
- // @Test
- // public void testDeleteOldVersionsResourceWithArtifacts(){
- // // simulate
- // Resource resource = createFullTestResource(checkinUser.getUserId(),
- // "1.0", LifecycleStateEnum.CERTIFIED);
- //
- // // checkout
- // Either<Resource, StorageOperationStatus> checkoutResource =
- // lifecycleOperation.checkoutResource(resource, checkinUser, checkinUser,
- // false);
- // assertTrue(checkoutResource.isLeft());
- // Either<Resource, StorageOperationStatus> getResource =
- // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(),
- // "1.1", false);
- // assertTrue(getResource.isLeft());
- //
- // // rfc
- // resource = getResource.left().value();
- // Either<Resource, StorageOperationStatus> requestCertification =
- // lifecycleOperation.requestCertification(resource, rfcUser, checkinUser,
- // false);
- // assertTrue(requestCertification.isLeft());
- // getResource =
- // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(),
- // "1.1", false);
- // assertTrue(getResource.isLeft());
- //
- // // start cert
- // resource = getResource.left().value();
- // Either<Resource, StorageOperationStatus> startCertification =
- // lifecycleOperation.startCertificationResource(resource, testerUser,
- // rfcUser, false);
- // assertTrue(startCertification.isLeft());
- // getResource =
- // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(),
- // "1.1", false);
- // assertTrue(getResource.isLeft());
- //
- // // certify
- // resource = getResource.left().value();
- // Either<Resource, StorageOperationStatus> certify =
- // lifecycleOperation.certifyResource(resource, testerUser, testerUser,
- // false);
- // assertTrue(certify.isLeft());
- // getResource =
- // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(),
- // "1.1", false);
- // assertTrue(getResource.isLeft());
- // resource = getResource.left().value();
- //
- //
- // Either<List<ArtifactDefinition>, StorageOperationStatus>
- // deleteOldComponentVersions = lifecycleOperation
- // .deleteOldComponentVersions(NodeTypeEnum.Resource,
- // resource.getResourceName(), resource.getUUID(), false);
- //
- // assertTrue(deleteOldComponentVersions.isLeft());
- // assertEquals(2, deleteOldComponentVersions.left().value().size());
- //
- // String resourceName = resource.getResourceName();
- // getResource = resourceOperation.getResourceByNameAndVersion(resourceName,
- // "1.0", false);
- // assertTrue(getResource.isLeft());
- //
- // getResource = resourceOperation.getResourceByNameAndVersion(resourceName,
- // "2.0", false);
- // assertTrue(getResource.isLeft());
- //
- // getResource = resourceOperation.getResourceByNameAndVersion(resourceName,
- // "1.1", false);
- // assertTrue(getResource.isRight());
- // assertEquals(StorageOperationStatus.NOT_FOUND,
- // getResource.right().value());
- //
- // }
-
- // @Test
- // public void testDeleteOldVersionsResourceWithArtifactsDerived(){
- // // simulate
- // Resource resourceRoot = createFullTestResource(checkinUser.getUserId(),
- // "1.0", LifecycleStateEnum.CERTIFIED);
- // Resource resource = buildResourceMetadata(checkinUser.getUserId(),
- // CATEGORY_NAME);
- // resource.setResourceName("myDerivedResource");
- // resource.setResourceVersion("0.1");
- // resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- // List<String> derived = new ArrayList<>();
- // derived.add(resourceRoot.getResourceName());
- // resource.setDerivedFrom(derived);
- //
- // Either<Resource, StorageOperationStatus> result =
- // resourceOperation.createResource(resource);
- // assertEquals("check resource created", true, result.isLeft());
- // resource = result.left().value();
- //
- // // resource inherits the artifacts from parent
- // assertNotNull(resource.getInterfaces().get(INTERFACE_NAME).getOperations().get(INTERFACE_OPERATION_CREATE).getImplementation());
- //
- // // rfc
- // Either<Resource, StorageOperationStatus> requestCertification =
- // lifecycleOperation.requestCertification(resource, rfcUser, checkinUser,
- // false);
- // assertTrue(requestCertification.isLeft());
- // Either<Resource, StorageOperationStatus> getResource =
- // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(),
- // "0.1", false);
- // assertTrue(getResource.isLeft());
- //
- // // start cert
- // resource = getResource.left().value();
- // Either<Resource, StorageOperationStatus> startCertification =
- // lifecycleOperation.startCertificationResource(resource, testerUser,
- // rfcUser, false);
- // assertTrue(startCertification.isLeft());
- // getResource =
- // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(),
- // "0.1", false);
- // assertTrue(getResource.isLeft());
- //
- // // certify
- // resource = getResource.left().value();
- // Either<Resource, StorageOperationStatus> certify =
- // lifecycleOperation.certifyResource(resource, testerUser, testerUser,
- // false);
- // assertTrue(certify.isLeft());
- // getResource =
- // resourceOperation.getResourceByNameAndVersion(resource.getResourceName(),
- // "0.1", false);
- // assertTrue(getResource.isLeft());
- // resource = getResource.left().value();
- //
- //
- // Either<List<ArtifactDefinition>, StorageOperationStatus>
- // deleteOldComponentVersions = lifecycleOperation
- // .deleteOldComponentVersions(NodeTypeEnum.Resource,
- // resource.getResourceName(), resource.getUUID(), false);
- //
- // assertTrue(deleteOldComponentVersions.isLeft());
- //
- // // resource artifacts are not really the resource's, they are the
- // parent's artifacts
- // assertTrue(deleteOldComponentVersions.left().value().isEmpty());
- //
- // String resourceName = resource.getResourceName();
- // getResource = resourceOperation.getResourceByNameAndVersion(resourceName,
- // "1.0", false);
- // assertTrue(getResource.isLeft());
- //
- // getResource = resourceOperation.getResourceByNameAndVersion(resourceName,
- // "0.1", false);
- // assertTrue(getResource.isRight());
- // assertEquals(StorageOperationStatus.NOT_FOUND,
- // getResource.right().value());
- //
- // }
-
- @Test
- @Ignore
- public void testDeleteOldVersionsService() {
- // simulate
- createTestService(checkinUser.getUserId(), "1.0", LifecycleStateEnum.CERTIFIED, null);
- Service serviceNewUUid = createTestService(checkinUser.getUserId(), "1.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
- createTestService(checkinUser.getUserId(), "1.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, serviceNewUUid.getUUID());
- createTestService(checkinUser.getUserId(), "1.3", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS, serviceNewUUid.getUUID());
- Service certifiedService = createTestService(checkinUser.getUserId(), "2.0", LifecycleStateEnum.CERTIFIED, serviceNewUUid.getUUID());
-
- Either<Boolean, StorageOperationStatus> deleteOldComponentVersions = lifecycleOperation.deleteOldComponentVersions(NodeTypeEnum.Service, certifiedService.getName(), certifiedService.getUUID(), false);
-
- assertTrue(deleteOldComponentVersions.isLeft());
-
- String resourceName = certifiedService.getName();
- Either<Service, StorageOperationStatus> service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.0", null, false);
- assertTrue(service.isLeft());
-
- service = serviceOperation.getServiceByNameAndVersion(resourceName, "2.0", null, false);
- assertTrue(service.isLeft());
-
- service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.1", null, false);
- /*
- * assertTrue(resource.isRight()); assertEquals(StorageOperationStatus.NOT_FOUND, resource.right().value());
- */
- assertTrue(service.isLeft());
- assertTrue(service.left().value().getIsDeleted());
-
- service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.2", null, false);
-
- service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.3", null, false);
- /*
- * assertTrue(service.isRight()); assertEquals(StorageOperationStatus.NOT_FOUND, service.right().value());
- */
- assertTrue(service.isLeft());
- assertTrue(service.left().value().getIsDeleted());
-
- service = serviceOperation.getServiceByNameAndVersion(resourceName, "1.3", null, false);
- /*
- * assertTrue(service.isRight()); assertEquals(StorageOperationStatus.NOT_FOUND, service.right().value());
- */
- assertTrue(service.isLeft());
- assertTrue(service.left().value().getIsDeleted());
-
- }
-
- private Resource certificationStatusChange(LifecycleStateEnum nextState, User expectedOwner) {
- Resource resultResource = createTestResource(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
-
- // certification request
- Either<Resource, StorageOperationStatus> requestCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, rfcUser, checkinUser, false);
- assertTrue(requestCertificationResult.isLeft());
-
- // start certification
- Either<Resource, StorageOperationStatus> startCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource, testerUser, rfcUser, false);
- assertEquals(true, startCertificationResult.isLeft());
- Resource actualResource = startCertificationResult.left().value();
-
- // cancel certification
- Either<Resource, StorageOperationStatus> failCertificationResult = (Either<Resource, StorageOperationStatus>) lifecycleOperation.cancelOrFailCertification(NodeTypeEnum.Resource, actualResource, testerUser, testerUser, nextState, false);
-
- assertEquals(true, failCertificationResult.isLeft());
- actualResource = failCertificationResult.left().value();
-
- // get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(actualResource.getUniqueId(), NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
- assertEquals(expectedOwner, resourceOwner);
-
- assertTrue(actualResource.isHighestVersion());
- assertEquals(checkinUser.getUserId(), actualResource.getCreatorUserId());
- assertEquals(testerUser.getUserId(), actualResource.getLastUpdaterUserId());
- assertEquals(nextState, actualResource.getLifecycleState());
- return actualResource;
- }
-
- private Service certificationStatusChangeService(LifecycleStateEnum nextState, User expectedOwner) {
- Service resultService = createTestService(checkinUser.getUserId(), "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, null);
-
- // certification request
- Either<? extends Component, StorageOperationStatus> requestCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, rfcUser, checkinUser, false);
- assertTrue(requestCertificationResult.isLeft());
-
- // start certification
- Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService, testerUser, rfcUser, false);
- assertEquals(true, startCertificationResult.isLeft());
- Service actualService = (Service) startCertificationResult.left().value();
-
- // cancel certification
- Either<? extends Component, StorageOperationStatus> failCertificationResult = lifecycleOperation.cancelOrFailCertification(NodeTypeEnum.Service, actualService, testerUser, testerUser, nextState, false);
-
- assertEquals(true, failCertificationResult.isLeft());
- actualService = (Service) failCertificationResult.left().value();
-
- // get resource owner
- Either<User, StorageOperationStatus> getOwnerResponse = lifecycleOperation.getComponentOwner(actualService.getUniqueId(), NodeTypeEnum.Resource, false);
-
- assertEquals("check user object is returned", true, getOwnerResponse.isLeft());
- User resourceOwner = getOwnerResponse.left().value();
- assertEquals(expectedOwner, resourceOwner);
-
- assertTrue(actualService.isHighestVersion());
- assertEquals(checkinUser.getUserId(), actualService.getCreatorUserId());
- assertEquals(testerUser.getUserId(), actualService.getLastUpdaterUserId());
- assertEquals(nextState, actualService.getLifecycleState());
- return actualService;
- }
-
- private Resource createTestResource(String userId, String version, LifecycleStateEnum state, String uuid) {
- // create resource in graph
-
- Resource resource2 = buildResourceMetadata(userId, CATEGORY_NAME);
- resource2.setVersion(version);
- ;
- resource2.setLifecycleState(state);
- resource2.setUUID(uuid);
-
- Either<Resource, StorageOperationStatus> result = resourceOperation.createResource(resource2);
- assertEquals("check resource created", true, result.isLeft());
- Resource resultResource = result.left().value();
- return resultResource;
- }
-
- private Service createTestService(String userId, String version, LifecycleStateEnum state, String uuid) {
- // create resource in graph
-
- Service service = new Service();
- service.setName(SERVICE_NAME);
- service.setVersion(version);
- service.setDescription("description 1");
- service.setCreatorUserId(userId);
- service.setContactId("contactId@sdc.com");
- CategoryDefinition category = new CategoryDefinition();
- category.setName(CATEGORY_NAME);
-
- List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(category);
- service.setCategories(categories);
- service.setIcon("images/my.png");
- List<String> tags = new ArrayList<String>();
- tags.add("TAG1");
- tags.add("TAG2");
- service.setTags(tags);
- service.setUUID(uuid);
-
- service.setLifecycleState(state);
-
- Either<Service, StorageOperationStatus> result = serviceOperation.createService(service);
- assertEquals("check service created", true, result.isLeft());
- Service resultResource = result.left().value();
- return resultResource;
- }
-
- private Resource createFullTestResource(String userId, String version, LifecycleStateEnum state) {
- Resource resource2 = buildResourceMetadata(userId, CATEGORY_NAME);
- resource2.setVersion(version);
- ;
- resource2.setLifecycleState(state);
-
- InterfaceDefinition inter = new InterfaceDefinition(INTERFACE_NAME, "interface description", null);
- // inter.setUniqueId(UniqueIdBuilder.buildResourceUniqueId(resource2.getResourceName(),
- // resource2.getResourceVersion())+"."+INTERFACE_NAME);
-
- Operation operation = new Operation();
- operation.setDescription("op description");
- operation.setUniqueId(inter.getUniqueId() + "." + INTERFACE_OPERATION_CREATE);
-
- ArtifactDataDefinition artifactDataDef = new ArtifactDataDefinition();
- artifactDataDef.setArtifactChecksum("YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI=");
- artifactDataDef.setArtifactName("create_myRoot.sh");
- artifactDataDef.setArtifactLabel("create_myRoot");
- artifactDataDef.setArtifactType("SHELL");
- artifactDataDef.setDescription("good description");
- artifactDataDef.setEsId("esId");
- artifactDataDef.setUniqueId(operation.getUniqueId() + "." + artifactDataDef.getArtifactLabel());
- ArtifactDefinition artifactDef = new ArtifactDefinition(artifactDataDef, "UEsDBAoAAAAIAAeLb0bDQz");
-
- operation.setImplementation(artifactDef);
- operation.setCreationDate(System.currentTimeMillis());
- Map<String, Operation> ops = new HashMap<>();
- ops.put(INTERFACE_OPERATION_CREATE, operation);
- inter.setOperationsMap(ops);
-
- Map<String, InterfaceDefinition> interfaces = new HashMap<>();
- interfaces.put(INTERFACE_NAME, inter);
-
- resource2.setInterfaces(interfaces);
-
- String capabilityTypeName = CAPABILITY_HOSTED_ON;
- createCapabilityOnGraph(capabilityTypeName);
-
- // create capability definition
- CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
- capabilityDefinition.setDescription("my capability");
- capabilityDefinition.setType(capabilityTypeName);
- capabilityDefinition.setName(CAPABILITY_NAME);
- Map<String, List<CapabilityDefinition>> capabilities = new HashMap<>();
- List<String> validSourceTypes = new ArrayList<String>();
- validSourceTypes.add("tosca.nodes.SC");
- capabilityDefinition.setValidSourceTypes(validSourceTypes);
- List<CapabilityDefinition> caplist = new ArrayList<CapabilityDefinition>();
- caplist.add(capabilityDefinition);
- capabilities.put(capabilityTypeName, caplist);
- resource2.setCapabilities(capabilities);
-
- // add requirement definition
- RequirementDefinition reqDefinition = new RequirementDefinition();
- // reqDefinition.setNode(reqNodeName);
- // reqDefinition.setRelationship(reqRelationship);
-
- reqDefinition.setCapability(capabilityTypeName);
- reqDefinition.setName(REQUIREMENT_NAME);
- Map<String, List<RequirementDefinition>> requirements = new HashMap<>();
- List<RequirementDefinition> reqlist = new ArrayList<RequirementDefinition>();
- reqlist.add(reqDefinition);
- requirements.put(capabilityTypeName, reqlist);
- resource2.setRequirements(requirements);
-
- Either<Resource, StorageOperationStatus> result = resourceOperation.createResource(resource2);
- assertEquals("check resource created", true, result.isLeft());
- Resource resultResource = result.left().value();
-
- // add artifacts to resource
- // ArtifactDataDefinition artifactDataDef = new
- // ArtifactDataDefinition();
- artifactDataDef.setArtifactChecksum("YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI=");
- artifactDataDef.setArtifactName("create_myRoot.sh");
- artifactDataDef.setArtifactLabel("create_myRoot");
- artifactDataDef.setArtifactType("SHELL");
- artifactDataDef.setDescription("good description");
- artifactDataDef.setEsId("esId");
- artifactDataDef.setUniqueId(resultResource.getUniqueId() + "." + artifactDataDef.getArtifactLabel());
- artifactDef = new ArtifactDefinition(artifactDataDef, "UEsDBAoAAAAIAAeLb0bDQz");
- // artifacts.put("myArtifact", artifactDef);
- // resource2.setArtifacts(artifacts);
-
- Either<ArtifactDefinition, StorageOperationStatus> addArifactToResource = artifactOperation.addArifactToComponent(artifactDef, resultResource.getUniqueId(), NodeTypeEnum.Resource, false, true);
- assertTrue(addArifactToResource.isLeft());
-
- Either<Resource, StorageOperationStatus> resource = resourceOperation.getResource(resultResource.getUniqueId());
- assertTrue(resource.isLeft());
-
- Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
- String json = prettyGson.toJson(resource.left().value());
- log.debug(json);
- return resource.left().value();
- }
-
- private void createCapabilityOnGraph(String capabilityTypeName) {
-
- CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition();
- capabilityTypeDefinition.setDescription("desc1");
- capabilityTypeDefinition.setType(capabilityTypeName);
- Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>();
- String propName1 = "disk_size";
- PropertyDefinition property1 = buildProperty1();
- properties.put(propName1, property1);
- capabilityTypeDefinition.setProperties(properties);
-
- Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType1 = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition);
- assertTrue(addCapabilityType1.isLeft());
- }
-
- private User convertUserDataToUser(UserData modifierData) {
- User modifier = new User();
- modifier.setUserId(modifierData.getUserId());
- modifier.setEmail(modifierData.getEmail());
- modifier.setFirstName(modifierData.getFirstName());
- modifier.setLastName(modifierData.getLastName());
- modifier.setRole(modifierData.getRole());
- return modifier;
- }
-
- private Resource buildResourceMetadata(String userId, String category) {
- // deleteAndCreateCategory(category);
-
- Resource resource = new Resource();
- resource.setName("my-resource");
- resource.setVersion("1.0");
- ;
- resource.setDescription("description 1");
- resource.setAbstract(false);
- resource.setCreatorUserId(userId);
- resource.setContactId("contactId@sdc.com");
- resource.setVendorName("vendor 1");
- resource.setVendorRelease("1.0.0");
- String[] categoryArr = category.split("/");
- resource.addCategory(categoryArr[0], categoryArr[1]);
- resource.setIcon("images/my.png");
- List<String> tags = new ArrayList<String>();
- tags.add("TAG1");
- tags.add("TAG2");
- resource.setTags(tags);
- return resource;
- }
-
- public UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) {
- UserData userData = new UserData();
- userData.setUserId(userId);
- userData.setFirstName(firstName);
- userData.setLastName(lastName);
- userData.setRole(role);
-
- titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class);
- titanGenericDao.createNode(userData, UserData.class);
- titanGenericDao.commit();
-
- return userData;
- }
-
- /*
- * public void deleteAndCreateCategory(String category) { CategoryData categoryData = new CategoryData(); categoryData.setName(category);
- *
- * Either<CategoryData, TitanOperationStatus> node = titanGenericDao.getNode(categoryData.getUniqueIdKey(), categoryData, CategoryData.class); if (node.isRight()){ //titanGenericDao.deleteNode(categoryData, CategoryData.class);
- * Either<CategoryData, TitanOperationStatus> createNode = titanGenericDao .createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode); }
- */
-
- private PropertyDefinition buildProperty1() {
- PropertyDefinition property1 = new PropertyDefinition();
- property1.setDefaultValue("10");
- property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
- property1.setType(ToscaType.INTEGER.name().toLowerCase());
- List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>();
- GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0");
- constraints.add(propertyConstraint1);
-
- LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10");
- constraints.add(propertyConstraint2);
-
- property1.setConstraints(constraints);
- return property1;
- }
-
- private ArtifactDefinition addArtifactToService(String userId, String serviceId, String artifactName) {
- ArtifactDefinition artifactInfo = new ArtifactDefinition();
-
- artifactInfo.setArtifactName(artifactName + ".sh");
- artifactInfo.setArtifactType("SHELL");
- artifactInfo.setDescription("hdkfhskdfgh");
- artifactInfo.setPayloadData("UEsDBAoAAAAIAAeLb0bDQz");
-
- artifactInfo.setUserIdCreator(userId);
- String fullName = "Jim H";
- artifactInfo.setUpdaterFullName(fullName);
- long time = System.currentTimeMillis();
- artifactInfo.setCreatorFullName(fullName);
- artifactInfo.setCreationDate(time);
- artifactInfo.setLastUpdateDate(time);
- artifactInfo.setUserIdLastUpdater(userId);
- artifactInfo.setArtifactLabel(artifactName);
- artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(serviceId, artifactInfo.getArtifactLabel()));
-
- Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation.addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true);
- assertTrue(artifact.isLeft());
- return artifactInfo;
- }
-
-}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java
deleted file mode 100644
index 62e6adab7f..0000000000
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperationTest.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.CapabiltyInstance;
-import org.openecomp.sdc.be.model.ModelTestBase;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil;
-import org.openecomp.sdc.be.resources.data.UserData;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-import fj.data.Either;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration("classpath:application-context-test.xml")
-public class RequirementOperationTest extends ModelTestBase {
- private static Logger log = LoggerFactory.getLogger(RequirementOperationTest.class.getName());
- private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
-
- private static String USER_ID = "muUserId";
- private static String CATEGORY_NAME = "category/mycategory";
-
- @javax.annotation.Resource(name = "titan-generic-dao")
- private TitanGenericDao titanDao;
-
- @javax.annotation.Resource(name = "requirement-operation")
- private RequirementOperation requirementOperation;
-
- @javax.annotation.Resource(name = "resource-operation")
- private ResourceOperation resourceOperation;
-
- @javax.annotation.Resource(name = "property-operation")
- private PropertyOperation propertyOperation;
-
- @javax.annotation.Resource(name = "capability-operation")
- private CapabilityOperation capabilityOperation;
-
- @javax.annotation.Resource(name = "capability-type-operation")
- private CapabilityTypeOperation capabilityTypeOperation;
-
- @BeforeClass
- public static void setupBeforeClass() {
-
- // configurationManager = new ConfigurationManager(
- // new ConfigurationSource() {
- //
- // @Override
- // public <T> T getAndWatchConfiguration(Class<T> className,
- // ConfigurationListener configurationListener) {
- // // TODO Auto-generated method stub
- // return null;
- // }
- //
- // @Override
- // public <T> void addWatchConfiguration(Class<T> className,
- // ConfigurationListener configurationListener) {
- // // TODO Auto-generated method stub
- //
- // }
- // });
- //
- // Configuration configuration = new Configuration();
- // configuration.setTitanInMemoryGraph(true);
- //
- // configurationManager.setConfiguration(configuration);
- ModelTestBase.init();
- }
-
- @Test
- public void testDummy() {
-
- assertTrue(requirementOperation != null);
-
- }
-
- @Test
- public void testAddRequirementNotExistCapability() {
-
- String reqName = "host";
- RequirementDefinition reqDefinition = new RequirementDefinition();
- reqDefinition.setNode("tosca.nodes.Compute");
- reqDefinition.setRelationship("myrelationship");
- reqDefinition.setCapability("mycapability___2");
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", "0.1", null, true, true);
-
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation.addRequirementToResource(reqName, reqDefinition, resource.getUniqueId());
- assertEquals("check error", StorageOperationStatus.INVALID_ID, addRequirementToResource.right().value());
-
- }
-
- @Before
- public void createUserAndCategory() {
- String[] category = CATEGORY_NAME.split("/");
- OperationTestsUtil.deleteAndCreateResourceCategory(category[0], category[1], titanDao);
- deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID);
- }
-
- private UserData deleteAndCreateUser(String userId, String firstName, String lastName) {
- UserData userData = new UserData();
- userData.setUserId(userId);
- userData.setFirstName(firstName);
- userData.setLastName(lastName);
-
- titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class);
- titanDao.createNode(userData, UserData.class);
- titanDao.commit();
-
- return userData;
- }
-
- /*
- * private void deleteAndCreateCategory(String category) { CategoryData categoryData = new CategoryData(); categoryData.setName(category);
- *
- * titanDao.deleteNode(categoryData, CategoryData.class); Either<CategoryData, TitanOperationStatus> createNode = titanDao .createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode);
- *
- * }
- */
-
- @Test
- @Ignore
- public void testAddRequirementWithCapability() {
-
- String capabilityTypeName = "tosca.nodes.Container";
-
- String reqName = "host";
- RequirementDefinition reqDefinition = new RequirementDefinition();
- reqDefinition.setNode("tosca.nodes.Compute");
- reqDefinition.setRelationship("myrelationship");
- reqDefinition.setCapability(capabilityTypeName);
-
- CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
- capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
-
- capabilityTypeOperationTest.createCapability(capabilityTypeName);
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", "2.0", null, true, true);
-
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation.addRequirementToResource(reqName, reqDefinition, resource.getUniqueId());
-
- assertEquals("check requirement was added", true, addRequirementToResource.isLeft());
-
- Either<Resource, StorageOperationStatus> resource2 = resourceOperation.getResource(resource.getUniqueId());
- String json = prettyGson.toJson(resource2);
- log.debug(json);
- }
-
- private void compareProperties(Map<String, PropertyDefinition> capabilityProperties, CapabiltyInstance capabiltyInstance, Map<String, String> actual) {
-
- Map<String, String> properties = capabiltyInstance.getProperties();
-
- for (Entry<String, PropertyDefinition> entry : capabilityProperties.entrySet()) {
- String paramName = entry.getKey();
- PropertyDefinition propertyDefinition = entry.getValue();
- String defaultValue = propertyDefinition.getDefaultValue();
-
- String value = properties.get(paramName);
-
- String actualValue = null;
- if (actual != null) {
- actualValue = actual.get(paramName);
- }
- if (actualValue != null) {
- assertEquals("check property value of key " + paramName, value, actualValue);
- } else {
- assertEquals("check property value of key " + paramName, value, defaultValue);
- }
- }
-
- }
-
-}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java
deleted file mode 100644
index e631f6ca42..0000000000
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceInstanceOperationTest.java
+++ /dev/null
@@ -1,2250 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.regex.Pattern;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.HeatParameterDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.ModelTestBase;
-import org.openecomp.sdc.be.model.RelationshipImpl;
-import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
-import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.ArtifactOperation;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityOperation;
-import org.openecomp.sdc.be.model.operations.impl.CapabilityTypeOperation;
-import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
-import org.openecomp.sdc.be.model.operations.impl.HeatParametersOperation;
-import org.openecomp.sdc.be.model.operations.impl.PropertyOperation;
-import org.openecomp.sdc.be.model.operations.impl.RequirementOperation;
-import org.openecomp.sdc.be.model.operations.impl.ResourceOperation;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil;
-import org.openecomp.sdc.be.model.operations.impl.util.PrintGraph;
-import org.openecomp.sdc.be.resources.data.ArtifactData;
-import org.openecomp.sdc.be.resources.data.HeatParameterData;
-import org.openecomp.sdc.be.resources.data.HeatParameterValueData;
-import org.openecomp.sdc.be.resources.data.RelationshipInstData;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.openecomp.sdc.be.resources.data.ServiceMetadataData;
-import org.openecomp.sdc.be.resources.data.UniqueIdData;
-import org.openecomp.sdc.be.resources.data.UserData;
-import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-import fj.data.Either;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration("classpath:application-context-test.xml")
-public class ResourceInstanceOperationTest extends ModelTestBase {
- private static Logger log = LoggerFactory.getLogger(ResourceInstanceOperationTest.class.getName());
- private Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
-
- private static String USER_ID = "muUserId";
- private static String CATEGORY_NAME = "category/mycategory";
-
- @javax.annotation.Resource(name = "titan-generic-dao")
- private TitanGenericDao titanDao;
-
- @javax.annotation.Resource(name = "requirement-operation")
- private RequirementOperation requirementOperation;
-
- @javax.annotation.Resource(name = "resource-operation")
- private ResourceOperation resourceOperation;
-
- @javax.annotation.Resource(name = "property-operation")
- private PropertyOperation propertyOperation;
-
- @javax.annotation.Resource(name = "capability-operation")
- private CapabilityOperation capabilityOperation;
-
- @javax.annotation.Resource(name = "capability-type-operation")
- private CapabilityTypeOperation capabilityTypeOperation;
-
- @javax.annotation.Resource(name = "component-instance-operation")
- private ComponentInstanceOperation resourceInstanceOperation;
-
- @javax.annotation.Resource
- private HeatParametersOperation heatParameterOperation;
-
- @javax.annotation.Resource
- private ArtifactOperation artifactOperation;
-
- private String CAPABILITY_1 = "mycapability101";
- private String CAPABILITY_2 = "mycapability102";
-
- private Integer TEST_CLASS_NUMBER = 1;
-
- public final static Pattern COMPONENT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_]+");
-
- public final static Pattern COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_]+");
-
- @BeforeClass
- public static void setupBeforeClass() {
-
- // configurationManager = new ConfigurationManager(
- // new ConfigurationSource() {
- //
- // @Override
- // public <T> T getAndWatchConfiguration(Class<T> className,
- // ConfigurationListener configurationListener) {
- // // TODO Auto-generated method stub
- // return null;
- // }
- //
- // @Override
- // public <T> void addWatchConfiguration(Class<T> className,
- // ConfigurationListener configurationListener) {
- // // TODO Auto-generated method stub
- //
- // }
- // });
- //
- // Configuration configuration = new Configuration();
- //
- // ////inmemory
- // boolean useInMemory = true;
- // if (useInMemory) {
- // configuration.setTitanInMemoryGraph(true);
- // } else {
- // configuration.setTitanInMemoryGraph(false);
- // configuration.setTitanCfgFile("C:\\Git_work\\D2-SDnC\\catalog-be\\src\\main\\resources\\config\\titan.properties");
- // }
- //
- //
- //
- // configurationManager.setConfiguration(configuration);
- ModelTestBase.init();
- }
-
- public void setOperations(TitanGenericDao titanDao, CapabilityTypeOperation capabilityTypeOperation, RequirementOperation requirementOperation, CapabilityOperation capabilityOperation, ResourceOperation resourceOperation,
- PropertyOperation propertyOperation, ComponentInstanceOperation resourceInstanceOperation2) {
- this.titanDao = titanDao;
- this.capabilityTypeOperation = capabilityTypeOperation;
- this.capabilityOperation = capabilityOperation;
- this.requirementOperation = requirementOperation;
- this.resourceOperation = resourceOperation;
- this.propertyOperation = propertyOperation;
- this.resourceInstanceOperation = resourceInstanceOperation2;
- }
-
- @Test
- public void testDummy() {
-
- assertTrue(requirementOperation != null);
-
- }
-
- @Test
- public void testAddResourceInstanceInvalidServiceId() {
-
- try {
- ComponentInstance instance = buildResourceInstance("tosca.nodes.Apache.2.0", "1", "tosca.nodes.Apache");
-
- Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation.addComponentInstanceToContainerComponent("service1", NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false);
- assertEquals("check failed status - service is not in graph", true, status.isRight());
- assertEquals("check failed status value - service is not in graph", TitanOperationStatus.INVALID_ID, status.right().value());
- } finally {
- titanDao.rollback();
- }
-
- }
-
- @Test
- public void testAddResourceInstanceValidServiceIdInvalidResourceId() {
- try {
-
- ServiceMetadataData serviceData1 = createService("myservice1.1.0");
-
- ComponentInstance instance = buildResourceInstance("tosca.nodes.Apache.2.0", "1", "tosca.nodes.Apache");
-
- Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false);
-
- assertEquals("check failed status - service is not in graph", true, status.isRight());
- assertEquals("check failed status value - service is not in graph", TitanOperationStatus.INVALID_ID, status.right().value());
-
- } finally {
- titanDao.rollback();
- }
-
- }
-
- @Test
- public void testAddResourceInstanceValidServiceId() {
- try {
- String serviceName = "myservice1.1.0";
- String resourceName = "tosca.nodes.Apache.2.0";
- ServiceMetadataData serviceData1 = createService(serviceName);
- ResourceMetadataData resourceData = createResource(resourceName);
-
- ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(), "1", "tosca.nodes.Apache");
-
- Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false);
-
- assertEquals("check success status - service is not in graph", true, status.isLeft());
-
- ComponentInstance value = status.left().value();
- assertEquals("check name exists", "tosca.nodes.Apache 1", value.getName());
-
- ServiceMetadataData serviceData2 = deleteService(serviceName);
- ResourceMetadataData resourceData2 = deleteResource(resourceName);
-
- } finally {
- titanDao.rollback();
- }
- }
-
- @Test
- public void testUpdateResourceInstance() {
- try {
- String serviceName = "myservice1.1.0";
- String resourceName = "tosca.nodes.Apache.2.0";
- ServiceMetadataData serviceData1 = createService(serviceName);
- ResourceMetadataData resourceData = createResource(resourceName);
-
- ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(), "1", "tosca.nodes.Apache");
-
- Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false);
-
- ComponentInstance resourceInstance = status.left().value();
- Long creationTime = resourceInstance.getCreationTime();
- String name = resourceInstance.getName();
- assertEquals("check success status - service is not in graph", true, status.isLeft());
-
- ComponentInstance value = status.left().value();
- assertEquals("check name exists", "tosca.nodes.Apache 1", value.getName());
-
- Either<ComponentInstance, StorageOperationStatus> u1Res = resourceInstanceOperation.updateResourceInstance((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value, true);
- assertTrue("check update succeed", u1Res.isLeft());
-
- Long lastModificationTimeNC = value.getModificationTime();
- String desc = "AAAAA";
- String posX = "15";
- String posY = "12";
- String updatedName = "Shlokshlik";
- value.setDescription(desc);
- value.setPosX(posX);
- Either<ComponentInstance, StorageOperationStatus> u2Res = resourceInstanceOperation.updateResourceInstance((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value, true);
- assertTrue("check update succeed", u2Res.isLeft());
- assertEquals("check resource instance updated", desc, u2Res.left().value().getDescription());
- assertEquals("check resource instance updated", posX, u2Res.left().value().getPosX());
- assertEquals("check resource instance updated", resourceInstance.getPosY(), u2Res.left().value().getPosY());
- assertEquals("check modification time was not updated since it was supplied", u2Res.left().value().getModificationTime(), lastModificationTimeNC);
-
- Long lastModificationTime = value.getModificationTime();
- value.setPosY(posY);
- value.setModificationTime(null);
- value.setName(updatedName);
- Either<ComponentInstance, StorageOperationStatus> u3Res = resourceInstanceOperation.updateResourceInstance((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, resourceInstance.getUniqueId(), value, true);
- assertTrue("check update succeed", u3Res.isLeft());
- assertEquals("check resource instance updated", desc, u3Res.left().value().getDescription());
- assertEquals("check resource pos x updated", posX, u3Res.left().value().getPosX());
- assertEquals("check resource pos y updated", posY, u3Res.left().value().getPosY());
- assertTrue("check modification time was updated", u3Res.left().value().getModificationTime() >= lastModificationTime);
- assertEquals("check creation time was not updated", creationTime, u3Res.left().value().getCreationTime());
- assertEquals("check name was updated", updatedName, u3Res.left().value().getName());
-
- ServiceMetadataData serviceData2 = deleteService(serviceName);
- ResourceMetadataData resourceData2 = deleteResource(resourceName);
-
- } finally {
- titanDao.rollback();
- }
- }
-
- @Test
- public void testRemoveResourceInstance() {
- try {
- String serviceName = "myservice1.1.0";
- String resourceName = "tosca.nodes.Apache.2.0";
- ServiceMetadataData serviceData1 = createService(serviceName);
- ResourceMetadataData resourceData = createResource(resourceName);
-
- ComponentInstance instance = buildResourceInstance(resourceData.getMetadataDataDefinition().getUniqueId(), "1", "tosca.nodes.Apache");
-
- Either<ComponentInstance, TitanOperationStatus> status = resourceInstanceOperation.addComponentInstanceToContainerComponent((String) serviceData1.getUniqueId(), NodeTypeEnum.Service, "1", true, instance, NodeTypeEnum.Resource, false);
-
- assertEquals("check success status - service is not in graph", true, status.isLeft());
-
- ComponentInstance value = status.left().value();
- assertEquals("check name exists", "tosca.nodes.Apache 1", value.getName());
-
- Either<ComponentInstance, TitanOperationStatus> status1 = resourceInstanceOperation.removeComponentInstanceFromComponent(NodeTypeEnum.Service, serviceName, value.getUniqueId());
-
- assertTrue("check resource service was deleted.", status1.isLeft());
- assertEquals("check resource instance returned.", "tosca.nodes.Apache 1", status1.left().value().getName());
-
- ServiceMetadataData serviceData2 = deleteService(serviceName);
- ResourceMetadataData resourceData2 = deleteResource(resourceName);
-
- } finally {
- titanDao.rollback();
- }
- }
-
- @Test
- public void testRemoveResourceInstanceNotFound() {
- try {
- String serviceName = "myservice1.1.0";
- ServiceMetadataData serviceData1 = createService(serviceName);
-
- Either<ComponentInstance, TitanOperationStatus> status1 = resourceInstanceOperation.removeComponentInstanceFromComponent(NodeTypeEnum.Service, serviceName, "stam");
-
- assertTrue("check resource service was not deleted.", status1.isRight());
- assertEquals("check NOT_FOUND returned.", TitanOperationStatus.NOT_FOUND, status1.right().value());
-
- ServiceMetadataData serviceData2 = deleteService(serviceName);
-
- } finally {
- titanDao.rollback();
- }
- }
-
- public ServiceMetadataData createService(String serviceName) {
-
- ServiceMetadataData serviceData1 = new ServiceMetadataData();
- serviceData1.getMetadataDataDefinition().setUniqueId(serviceName);
- Either<ServiceMetadataData, TitanOperationStatus> createNode = titanDao.createNode(serviceData1, ServiceMetadataData.class);
-
- assertTrue("check service created", createNode.isLeft());
- return createNode.left().value();
- }
-
- public ServiceMetadataData deleteService(String serviceName) {
-
- ServiceMetadataData serviceData1 = new ServiceMetadataData();
- serviceData1.getMetadataDataDefinition().setUniqueId(serviceName);
- Either<ServiceMetadataData, TitanOperationStatus> createNode = titanDao.deleteNode(serviceData1, ServiceMetadataData.class);
- assertTrue("check service deleted", createNode.isLeft());
- return createNode.left().value();
- }
-
- public ResourceMetadataData createResource(String resourceName) {
-
- ResourceMetadataData serviceData1 = new ResourceMetadataData();
- serviceData1.getMetadataDataDefinition().setUniqueId(resourceName);
- Either<ResourceMetadataData, TitanOperationStatus> createNode = titanDao.createNode(serviceData1, ResourceMetadataData.class);
-
- assertTrue("check service created", createNode.isLeft());
- return createNode.left().value();
- }
-
- public ResourceMetadataData deleteResource(String resourceName) {
-
- ResourceMetadataData serviceData1 = new ResourceMetadataData();
- serviceData1.getMetadataDataDefinition().setUniqueId(resourceName);
- Either<ResourceMetadataData, TitanOperationStatus> createNode = titanDao.deleteNode(serviceData1, ResourceMetadataData.class);
-
- assertTrue("check service created", createNode.isLeft());
- return createNode.left().value();
- }
-
- @Test
- public void testAddResourceInstanceJson() {
- addResourceInstanceJson();
- }
-
- public ComponentInstance addResourceInstanceJson() {
-
- ComponentInstance resourceInstance = buildResourceInstance("tosca.nodes.Apache.2.0", "1", "tosca.nodes.Apache");
-
- String json = prettyGson.toJson(resourceInstance);
- log.debug(json);
-
- return resourceInstance;
-
- }
-
- private ComponentInstance buildResourceInstance(String respurceUid, String instanceNumber, String name) {
- ComponentInstance resourceInstance = new ComponentInstance();
- // resourceInstance
- // .setUniqueId("<SN>.tosca.nodes.Apache.2.0." + instanceNumber);
- resourceInstance.setName(name);
- resourceInstance.setDescription("desc1");
- resourceInstance.setPosX("20");
- resourceInstance.setPosY("40");
- resourceInstance.setComponentUid(respurceUid);
- resourceInstance.setCreationTime(System.currentTimeMillis());
- resourceInstance.setModificationTime(System.currentTimeMillis());
- resourceInstance.setNormalizedName(normaliseComponentInstanceName(name));
-
- // Map<String, RequirementInstance> requirements = new HashMap<String,
- // RequirementInstance>();
- //
- // RequirementInstance requirementInstance1 = new RequirementInstance();
- // requirementInstance1.setNode("NA");
- // RelationshipImpl relationshipImpl = new RelationshipImpl();
- // relationshipImpl.setType("tosca.relationships.HostedOn");
- // requirementInstance1.setRelationship(relationshipImpl);
- //
- // requirements.put("host", requirementInstance1);
- //
- // RequirementInstance requirementInstance2 = new RequirementInstance();
- // requirementInstance2.setNode("NA");
- // RelationshipImpl relationshipImpl2 = new RelationshipImpl();
- // relationshipImpl2.setType("tosca.relationships.LinkTo");
- // requirementInstance2.setRelationship(relationshipImpl2);
- //
- // requirements.put("link", requirementInstance2);
- //
- // resourceInstance.setRequirements(requirements);
- return resourceInstance;
- }
-
- @Test
- @Ignore
- public void testConenctResourceInstancesJson() {
- RequirementCapabilityRelDef addRelationship = addRelationship("apache_1", "compute_100");
- String json = prettyGson.toJson(addRelationship);
- log.debug(json);
-
- RequirementCapabilityRelDef capabilityRelDef = prettyGson.fromJson(json, RequirementCapabilityRelDef.class);
- log.debug("{}", capabilityRelDef);
-
- }
-
- public RequirementCapabilityRelDef addRelationship(String from, String to) {
- RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef();
- requirementCapabilityRelDef.setFromNode(from);
- requirementCapabilityRelDef.setToNode(to);
- List<RequirementAndRelationshipPair> relationships = new ArrayList<RequirementAndRelationshipPair>();
-
- String req = "host";
- RelationshipImpl relationshipImpl = new RelationshipImpl();
- relationshipImpl.setType("tosca.nodes.HostedOn");
- RequirementAndRelationshipPair rels = new RequirementAndRelationshipPair(req, relationshipImpl);
- relationships.add(rels);
-
- requirementCapabilityRelDef.setRelationships(relationships);
-
- return requirementCapabilityRelDef;
- }
-
- @Before
- public void createUserAndCategory() {
- deleteAndCreateCategory(CATEGORY_NAME);
- deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID);
- }
-
- private UserData deleteAndCreateUser(String userId, String firstName, String lastName) {
- UserData userData = new UserData();
- userData.setUserId(userId);
- userData.setFirstName(firstName);
- userData.setLastName(lastName);
-
- titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class);
- titanDao.createNode(userData, UserData.class);
- titanDao.commit();
-
- return userData;
- }
-
- private void deleteAndCreateCategory(String category) {
- String[] names = category.split("/");
- OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao);
- OperationTestsUtil.deleteAndCreateServiceCategory(category, titanDao);
-
- /*
- * CategoryData categoryData = new CategoryData(); categoryData.setName(category);
- *
- * titanDao.deleteNode(categoryData, CategoryData.class); Either<CategoryData, TitanOperationStatus> createNode = titanDao .createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode);
- */
- }
-
- @Test
- @Ignore
- public void testConnectResourceInstances() {
-
- PrintGraph printGraph1 = new PrintGraph();
- int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value());
- try {
-
- String capabilityTypeName = CAPABILITY_2;
- String reqName = "host";
- String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER;
- String rootName = "Root2" + TEST_CLASS_NUMBER;
- String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER;
- String computeNodeName = reqNodeName;
- String myResourceVersion = "4.0" + TEST_CLASS_NUMBER;
- String reqRelationship = "myrelationship";
-
- // Create Capability type
- CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
- capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName);
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- // create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
-
- String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
- log.debug(rootResourceJson);
-
- // create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
-
- resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- // create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
-
- // rollbackAndPrint();
-
- // Add capabilities to Compute Resource
- CapabilityDefinition addCapability = addCapabilityToResource(capabilityTypeName, "host", computeComponent);
-
- // create requirement definition
-
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent);
-
- String parentReqUniqId = addRequirementToResource.left().value().getUniqueId();
-
- // create my resource derived from software component
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true);
-
- String serviceName = "myservice.1.0";
- List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, computeComponent, "host", false, addCapability.getUniqueId(), addRequirementToResource.left().value().getUniqueId());
-
- PrintGraph printGraph = new PrintGraph();
- String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value());
- log.debug(webGraph);
-
- Either<Resource, StorageOperationStatus> resourceFull = resourceOperation.getResource(resource.getUniqueId());
- assertTrue(resourceFull.isLeft());
- List<RequirementCapabilityRelDef> componentInstancesRelations = resourceFull.left().value().getComponentInstancesRelations();
-
- RequirementCapabilityRelDef capabilityRelDef = componentInstancesRelations.get(0);
- capabilityRelDef.getRelationships().get(0).setRequirement("host");
-
- // disconnectResourcesInService(serviceName, resInstances.get(0),
- // "host");
- disconnectResourcesInService(serviceName, capabilityRelDef);
-
- } finally {
- rollbackAndPrint(false);
- compareGraphSize(numberOfVertices);
- }
-
- }
-
- @Test
- @Ignore
- public void testConnectResourceInstances1Requirement2Capabilities() {
-
- PrintGraph printGraph1 = new PrintGraph();
- int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value());
-
- try {
-
- String capabilityTypeName1 = CAPABILITY_1;
- String capabilityTypeName2 = CAPABILITY_2;
- String reqName1 = "host1";
- String reqName2 = "host2";
- String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER;
- String rootName = "Root2" + TEST_CLASS_NUMBER;
- String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER;
- String computeNodeName = reqNodeName;
- String myResourceVersion = "4.0" + TEST_CLASS_NUMBER;
- String reqRelationship = "myrelationship";
-
- // Create Capability type
- CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
- capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest.createCapability(capabilityTypeName1);
- CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest.createCapability(capabilityTypeName2);
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- // create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
-
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
-
- String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
- log.debug(rootResourceJson);
-
- // create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
-
- resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- // create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
-
- // Add capabilities to Compute Resource
- CapabilityDefinition capabilty1 = addCapabilityToResource(capabilityTypeName1, reqName1, computeComponent);
- CapabilityDefinition capabilty2 = addCapabilityToResource(capabilityTypeName2, reqName2, computeComponent);
-
- // rollbackAndPrint();
-
- // create requirement definition
-
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent);
-
- String requirementId = addRequirementToResource.left().value().getUniqueId();
- String parentReqUniqId = requirementId;
-
- // create my resource derived from software component
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true);
-
- String serviceName = "myservice.1.0";
- List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, computeComponent, reqName1, false, capabilty1.getUniqueId(), requirementId);
-
- PrintGraph printGraph = new PrintGraph();
- String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value());
- log.debug(webGraph);
-
- RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
- relationPair.setRequirement(reqName2);
-
- relationPair.setCapabilityUid(capabilty1.getUniqueId());
- relationPair.setRequirementUid(requirementId);
-
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService1 = resourceInstanceOperation.connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(), resInstances.get(1).getUniqueId(),
- relationPair);
- assertEquals("check cannot associate resource instances", TitanOperationStatus.ILLEGAL_ARGUMENT, connectResourcesInService1.right().value());
- relationPair.setRequirement(reqName1);
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService2 = resourceInstanceOperation.connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(), resInstances.get(1).getUniqueId(),
- relationPair);
- assertEquals("check cannot associate resource instances", TitanOperationStatus.TITAN_SCHEMA_VIOLATION, connectResourcesInService2.right().value());
-
- relationPair.setRequirement(reqName1);
-
- RequirementCapabilityRelDef capabilityRelDef = new RequirementCapabilityRelDef();
- capabilityRelDef.setFromNode(resInstances.get(0).getUniqueId());
- capabilityRelDef.setToNode(resInstances.get(1).getUniqueId());
- List<RequirementAndRelationshipPair> list = new ArrayList<>();
- list.add(relationPair);
-
- disconnectResourcesInService(serviceName, capabilityRelDef);
-
- } finally {
- rollbackAndPrint();
- compareGraphSize(numberOfVertices);
- }
-
- }
-
- private void rollbackAndPrint() {
- rollbackAndPrint(false);
- }
-
- private void rollbackAndPrint(boolean print) {
- TitanOperationStatus rollback = titanDao.rollback();
- if (print) {
- log.debug("rollback status={}", rollback);
- PrintGraph printGraph = new PrintGraph();
- printGraph.printGraphVertices(titanDao.getGraph().left().value());
- }
- }
-
- @Test
- @Ignore
- public void testConnectResourceInstances2Requirement2Capabilities() {
-
- PrintGraph printGraph1 = new PrintGraph();
- int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value());
-
- try {
-
- String capabilityTypeName1 = CAPABILITY_1;
- String capabilityTypeName2 = CAPABILITY_2;
- String reqName1 = "host1";
- String reqName2 = "host2";
- String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER;
- String rootName = "Root2" + TEST_CLASS_NUMBER;
- String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER;
- String computeNodeName = reqNodeName;
- String myResourceVersion = "4.0" + TEST_CLASS_NUMBER;
- String reqRelationship = "myrelationship";
-
- // Create Capability type
- CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
- capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest.createCapability(capabilityTypeName1);
- CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest.createCapability(capabilityTypeName2);
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- // create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
-
- String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
- log.debug(rootResourceJson);
-
- // rollbackAndPrint();
- // OKKKKKKK
-
- // create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
-
- resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- // create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
-
- // rollbackAndPrint();
- // OKKKKKKKKKK
-
- // Add capabilities to Compute Resource
- CapabilityDefinition capabilty1 = addCapabilityToResource(capabilityTypeName1, reqName1, computeComponent);
- CapabilityDefinition capabilty2 = addCapabilityToResource(capabilityTypeName2, reqName2, computeComponent);
-
- // rollbackAndPrint();
-
- // create requirement definition
-
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource1 = addRequirementToResource(capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent);
-
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource2 = addRequirementToResource(capabilityTypeName2, reqName2, reqNodeName, reqRelationship, softwareComponent);
-
- // create my resource derived from software component
- String MY_RESOURCE = "my-resource";
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, MY_RESOURCE, myResourceVersion, softwareComponent.getName(), true, true);
-
- String serviceName = "myservice.1.0";
- String requirementId1 = addRequirementToResource1.left().value().getUniqueId();
- String requirementId2 = addRequirementToResource2.left().value().getUniqueId();
- List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, computeComponent, reqName1, false, capabilty1.getUniqueId(), requirementId1);
-
- RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
- relationPair.setRequirement(reqName2);
- relationPair.setCapabilityUid(capabilty2.getUniqueId());
- relationPair.setRequirementUid(requirementId2);
- relationPair.setCapabilityOwnerId(resInstances.get(1).getUniqueId());
- relationPair.setRequirementOwnerId(resInstances.get(0).getUniqueId());
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService1 = resourceInstanceOperation.connectResourcesInService(serviceName, NodeTypeEnum.Service, resInstances.get(0).getUniqueId(), resInstances.get(1).getUniqueId(),
- relationPair);
- assertTrue("check associate resource instances succeed " + reqName2, connectResourcesInService1.isLeft());
-
- // rollbackAndPrint();
-
- PrintGraph printGraph = new PrintGraph();
- String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value());
- log.debug(webGraph);
-
- RequirementCapabilityRelDef reqCapDef = new RequirementCapabilityRelDef();
- reqCapDef.setFromNode(resInstances.get(0).getUniqueId());
- reqCapDef.setToNode(resInstances.get(1).getUniqueId());
-
- relationPair.setRequirement(reqName1);
- relationPair.setCapabilityUid(capabilty1.getUniqueId());
- relationPair.setRequirementUid(requirementId1);
- RelationshipImpl relationship = new RelationshipImpl();
- relationship.setType(reqName1);
- relationPair.setRelationships(relationship);
-
- List<RequirementAndRelationshipPair> list = new ArrayList<>();
- list.add(relationPair);
- reqCapDef.setRelationships(list);
-
- disconnectResourcesInService(serviceName, reqCapDef);
-
- reqCapDef.getRelationships().clear();
-
- RequirementAndRelationshipPair relationPair1 = new RequirementAndRelationshipPair();
- relationPair1.setRequirement(reqName2);
- relationPair1.setCapabilityUid(capabilty2.getUniqueId());
- relationPair1.setRequirementUid(requirementId2);
- relationPair1.setCapabilityOwnerId(resInstances.get(1).getUniqueId());
- relationPair1.setRequirementOwnerId(resInstances.get(0).getUniqueId());
- relationship.setType(reqName2);
- relationPair1.setRelationships(relationship);
- reqCapDef.getRelationships().add(relationPair1);
-
- disconnectResourcesInService(serviceName, reqCapDef);
-
- RequirementCapabilityRelDef relation = new RequirementCapabilityRelDef();
- String fromResUid = resInstances.get(0).getUniqueId();
- String toResUid = resInstances.get(1).getUniqueId();
- relation.setFromNode(fromResUid);
- relation.setToNode(toResUid);
- List<RequirementAndRelationshipPair> relationships = new ArrayList<RequirementAndRelationshipPair>();
- RequirementAndRelationshipPair immutablePair1 = new RequirementAndRelationshipPair(reqName1, null);
- RequirementAndRelationshipPair immutablePair2 = new RequirementAndRelationshipPair(reqName2, null);
- immutablePair1.setCapabilityUid(capabilty1.getUniqueId());
- immutablePair1.setRequirementUid(addRequirementToResource1.left().value().getUniqueId());
- immutablePair1.setRequirementOwnerId(resInstances.get(0).getUniqueId());
- immutablePair1.setCapabilityOwnerId(resInstances.get(1).getUniqueId());
-
- immutablePair2.setCapabilityUid(capabilty2.getUniqueId());
- immutablePair2.setRequirementUid(addRequirementToResource2.left().value().getUniqueId());
- immutablePair2.setRequirementOwnerId(resInstances.get(0).getUniqueId());
- immutablePair2.setCapabilityOwnerId(resInstances.get(1).getUniqueId());
-
- relationships.add(immutablePair1);
- relationships.add(immutablePair2);
- relation.setRelationships(relationships);
-
- Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances = resourceInstanceOperation.associateResourceInstances(serviceName, NodeTypeEnum.Service, relation, true, false);
- assertTrue("check return code after associating 2 requirements in one request", associateResourceInstances.isLeft());
- RequirementCapabilityRelDef capabilityRelDef = associateResourceInstances.left().value();
- String fromNode = capabilityRelDef.getFromNode();
- assertEquals("check from node", resInstances.get(0).getUniqueId(), fromNode);
- String toNode = capabilityRelDef.getToNode();
- assertEquals("check to node", resInstances.get(1).getUniqueId(), toNode);
- List<RequirementAndRelationshipPair> relationships2 = capabilityRelDef.getRelationships();
- assertEquals("check number of relations", 2, relationships2.size());
-
- for (RequirementAndRelationshipPair pair : relationships2) {
- String key = pair.getRequirement();
- RelationshipImpl relationshipImpl = pair.getRelationship();
- if (key.equals(reqName1)) {
- String type = relationshipImpl.getType();
- assertEquals("Check relationship type name", reqRelationship, type);
- } else if (key.equals(reqName2)) {
- String type = relationshipImpl.getType();
- assertEquals("Check relationship type name", reqRelationship, type);
- } else {
- assertTrue("requirement " + key + " was not found in the original request", false);
- }
- }
-
- verifyGetAllResourceInstanceFromService(reqName1, reqName2, serviceName, fromResUid, toResUid);
-
- List<ResourceMetadataData> resourcesPathList = new ArrayList<ResourceMetadataData>();
- TitanOperationStatus findResourcesPathRecursively = resourceOperation.findResourcesPathRecursively(resource.getUniqueId(), resourcesPathList);
- assertEquals("check returned status", TitanOperationStatus.OK, findResourcesPathRecursively);
- assertEquals("check list size", 3, resourcesPathList.size());
-
- TitanOperationStatus validateTheTargetResourceInstance = resourceInstanceOperation.validateTheTargetResourceInstance(MY_RESOURCE, resource.getUniqueId());
- assertEquals("check resource name in the path", TitanOperationStatus.OK, validateTheTargetResourceInstance);
- validateTheTargetResourceInstance = resourceInstanceOperation.validateTheTargetResourceInstance(softwareCompName, resource.getUniqueId());
- assertEquals("check resource name in the path", TitanOperationStatus.OK, validateTheTargetResourceInstance);
-
- validateTheTargetResourceInstance = resourceInstanceOperation.validateTheTargetResourceInstance(softwareCompName + "STAM", resource.getUniqueId());
- assertEquals("check resource name not in the path", TitanOperationStatus.MATCH_NOT_FOUND, validateTheTargetResourceInstance);
-
- Either<ComponentInstance, StorageOperationStatus> deleteResourceInstance = resourceInstanceOperation.deleteComponentInstance(NodeTypeEnum.Service, serviceName, toResUid, true);
- assertTrue("check resource instance was deleted.", deleteResourceInstance.isLeft());
-
- } finally {
- rollbackAndPrint(false);
- compareGraphSize(numberOfVertices);
- }
-
- }
-
- private void verifyGetAllResourceInstanceFromService(String reqName1, String reqName2, String serviceName, String fromResUid, String toResUid) {
-
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceName, NodeTypeEnum.Service, NodeTypeEnum.Resource,
- true);
- // assertTrue("check return code after get all resource instances",
- // associateResourceInstances.isLeft());
- ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>> immutablePair = allResourceInstances.left().value();
- List<ComponentInstance> nodes = immutablePair.getKey();
- List<RequirementCapabilityRelDef> edges = immutablePair.getValue();
- assertEquals("check 2 nodes returned", 2, nodes.size());
- assertEquals("check one relation returned", 1, edges.size());
- RequirementCapabilityRelDef requirementCapabilityRelDef = edges.get(0);
- assertEquals("check from node", requirementCapabilityRelDef.getFromNode(), fromResUid);
- requirementCapabilityRelDef.getToNode();
- assertEquals("check to node", requirementCapabilityRelDef.getToNode(), toResUid);
- int size = requirementCapabilityRelDef.getRelationships().size();
- assertEquals("check number of relations", 2, size);
- String req1 = requirementCapabilityRelDef.getRelationships().get(0).getRequirement();
- String req2 = requirementCapabilityRelDef.getRelationships().get(1).getRequirement();
-
- List<String> requirements = new ArrayList<String>();
- requirements.add(req1);
- requirements.add(req2);
-
- assertTrue("check requirement returned " + reqName1, requirements.contains(reqName1));
- assertTrue("check requirement returned " + reqName2, requirements.contains(reqName2));
-
- String nodesStr = prettyGson.toJson(nodes);
- String edgesStr = prettyGson.toJson(edges);
-
- log.debug(nodesStr);
- log.debug(edgesStr);
- }
-
- private Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String capabilityTypeName1, String reqName1, String reqNodeName, String reqRelationship, Resource softwareComponent) {
- RequirementDefinition reqDefinition1 = new RequirementDefinition();
- reqDefinition1.setNode(reqNodeName);
- reqDefinition1.setRelationship(reqRelationship);
- reqDefinition1.setCapability(capabilityTypeName1);
- // add requirement to software component
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation.addRequirementToResource(reqName1, reqDefinition1, softwareComponent.getUniqueId(), true);
- assertEquals("check requirement was added", true, addRequirementToResource.isLeft());
- return addRequirementToResource;
- }
-
- private CapabilityDefinition addCapabilityToResource(String capabilityTypeName1, String reqName1, Resource computeComponent) {
- CapabilityDefinition capabilityDefinition1 = new CapabilityDefinition();
- capabilityDefinition1.setDescription("my capability");
- capabilityDefinition1.setType(capabilityTypeName1);
- List<String> validSourceTypes = new ArrayList<String>();
- validSourceTypes.add("tosca.nodes.SC");
- capabilityDefinition1.setValidSourceTypes(validSourceTypes);
- Either<CapabilityDefinition, StorageOperationStatus> addCapability = capabilityOperation.addCapability(computeComponent.getUniqueId(), reqName1, capabilityDefinition1, true);
- assertTrue("check capability created ", addCapability.isLeft());
- return addCapability.left().value();
- }
-
- @Test
- @Ignore
- public void testConnectResourceInstancesCapabilityNameDiffFromReqName() {
-
- PrintGraph printGraph1 = new PrintGraph();
- int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value());
-
- try {
-
- String capabilityTypeName = CAPABILITY_2;
- String reqName = "host";
- String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER;
- String rootName = "Root2" + TEST_CLASS_NUMBER;
- String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER;
- String computeNodeName = reqNodeName;
- String myResourceVersion = "4.0" + TEST_CLASS_NUMBER;
- String reqRelationship = "myrelationship";
-
- String DIFFERENT_CAPABILITY = "hostDiffernet";
-
- // Create Capability type
- CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
- capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName);
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- // create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
-
- String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
- log.debug(rootResourceJson);
-
- // create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
-
- resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- // create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
-
- CapabilityDefinition capabilty = addCapabilityToResource(capabilityTypeName, DIFFERENT_CAPABILITY, computeComponent);
-
- // create requirement definition
-
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent);
-
- String parentReqUniqId = addRequirementToResource.left().value().getUniqueId();
-
- // create my resource derived from software component
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true);
-
- String serviceName = "myservice.1.0";
- List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstances(serviceName, resource, computeComponent, "host", false, capabilty.getUniqueId(), parentReqUniqId);
-
- PrintGraph printGraph = new PrintGraph();
- String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value());
- } finally {
- rollbackAndPrint();
-
- compareGraphSize(numberOfVertices);
- }
-
- }
-
- @Test
- @Ignore
- public void testConnectResourceInstancesInvalidCapability() {
-
- PrintGraph printGraph1 = new PrintGraph();
- int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value());
-
- try {
-
- String capabilityTypeName = CAPABILITY_2;
- String reqName = "host";
- String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER;
- String rootName = "Root2" + TEST_CLASS_NUMBER;
- String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER;
- String computeNodeName = reqNodeName;
- String myResourceVersion = "4.0" + TEST_CLASS_NUMBER;
- String reqRelationship = "myrelationship";
-
- String capabilityTypeNameOther = CAPABILITY_2 + "othertype";
-
- String DIFFERENT_CAPABILITY = "hostDiffernet";
-
- // Create Capability type
- CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
- capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName);
-
- CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest.createCapability(capabilityTypeNameOther);
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- // create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
-
- String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
- log.debug(rootResourceJson);
-
- // create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
-
- resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- // create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
-
- addCapabilityToResource(capabilityTypeName, DIFFERENT_CAPABILITY, computeComponent);
-
- // create requirement definition
-
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(capabilityTypeNameOther, reqName, reqNodeName, reqRelationship, softwareComponent);
-
- String parentReqUniqId = addRequirementToResource.left().value().getUniqueId();
-
- // create my resource derived from software component
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true);
-
- String serviceName = "myservice.1.0";
- List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstancesWithError(serviceName, resource, computeComponent, "host", false, TitanOperationStatus.ILLEGAL_ARGUMENT);
-
- PrintGraph printGraph = new PrintGraph();
- String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value());
- log.debug(webGraph);
-
- } finally {
- rollbackAndPrint();
-
- compareGraphSize(numberOfVertices);
- }
-
- }
-
- private void compareGraphSize(int numberOfVertices, Set<String> toRemoveFromSet) {
- PrintGraph printGraph2 = new PrintGraph();
- int numberOfVerticesCurr = printGraph2.getNumberOfVertices(titanDao.getGraph().left().value());
-
- Set<String> set = printGraph2.getVerticesSet(titanDao.getGraph().left().value());
- if (toRemoveFromSet != null) {
- set.removeAll(toRemoveFromSet);
- }
-
- assertEquals("check all data deleted from graph " + set, numberOfVertices, numberOfVerticesCurr);
- }
-
- private void compareGraphSize(int numberOfVertices) {
- PrintGraph printGraph2 = new PrintGraph();
- int numberOfVerticesCurr = printGraph2.getNumberOfVertices(titanDao.getGraph().left().value());
-
- assertEquals("check all data deleted from graph " + printGraph2.getVerticesSet(titanDao.getGraph().left().value()), numberOfVertices, numberOfVerticesCurr);
- }
-
- @Test
- @Ignore
- public void testConnectResourceInstancesRequirementNotFound() {
-
- PrintGraph printGraph1 = new PrintGraph();
- int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value());
- try {
-
- String capabilityTypeName = CAPABILITY_2;
- String reqName = "host";
- String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER;
- String rootName = "Root2" + TEST_CLASS_NUMBER;
- String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER;
- String computeNodeName = reqNodeName;
- String myResourceVersion = "4.0" + TEST_CLASS_NUMBER;
- String reqRelationship = "myrelationship";
-
- String DIFFERENT_CAPABILITY = "hostDiffernet";
-
- // Create Capability type
- CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
- capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName);
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- // create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
-
- String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
- log.debug(rootResourceJson);
-
- // create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
-
- resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- // create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
-
- addCapabilityToResource(capabilityTypeName, reqName, computeComponent);
-
- // create requirement definition
-
- RequirementDefinition reqDefinition = new RequirementDefinition();
- reqDefinition.setNode(reqNodeName);
- reqDefinition.setRelationship(reqRelationship);
- reqDefinition.setCapability(capabilityTypeName);
- // add requirement to software component
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = requirementOperation.addRequirementToResource(reqName + "ssssssss", reqDefinition, softwareComponent.getUniqueId(), true);
- assertEquals("check requirement was added", true, addRequirementToResource.isLeft());
-
- String parentReqUniqId = addRequirementToResource.left().value().getUniqueId();
-
- // create my resource derived from software component
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true);
-
- String serviceName = "myservice.1.0";
- List<ComponentInstance> resInstances = buildServiceAndConnectBetweenResourceInstancesWithError(serviceName, resource, computeComponent, "host", false, TitanOperationStatus.ILLEGAL_ARGUMENT);
-
- PrintGraph printGraph = new PrintGraph();
- String webGraph = printGraph.buildGraphForWebgraphWiz(titanDao.getGraph().left().value());
- log.debug(webGraph);
-
- } finally {
- titanDao.rollback();
-
- compareGraphSize(numberOfVertices);
- }
-
- }
-
- private void disconnectResourcesInService(String serviceName, RequirementCapabilityRelDef reqCapDef) {
-
- Either<List<RelationshipInstData>, TitanOperationStatus> disconnectResourcesInService = resourceInstanceOperation.disconnectResourcesInService(serviceName, NodeTypeEnum.Service, reqCapDef);
- assertTrue("check relatioship instance was deleted", disconnectResourcesInService.isLeft());
-
- disconnectResourcesInService = resourceInstanceOperation.disconnectResourcesInService(serviceName, NodeTypeEnum.Service, reqCapDef);
- assertTrue("check relatioship instance already was deleted", disconnectResourcesInService.isRight());
- assertEquals("check relatioship instance already was deleted. status NOT_FOUND", TitanOperationStatus.NOT_FOUND, disconnectResourcesInService.right().value());
- }
-
- private List<ComponentInstance> buildServiceAndConnectBetweenResourceInstancesWithError(String serviceName, Resource resource, Resource computeComponent, String requirement, boolean ignoreCreatingService,
- TitanOperationStatus titanOperationStatus) {
-
- String serviceId = "myservice.1.0";
-
- if (false == ignoreCreatingService) {
- ServiceMetadataData createService = createService(serviceId);
- }
- ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", resource.getName());
-
- ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2", computeComponent.getName());
-
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
- assertTrue("check instance added to service", myinstanceRes.isLeft());
- ComponentInstance value1 = myinstanceRes.left().value();
- Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, NodeTypeEnum.Resource, false);
- assertTrue("check instance added to service", computeInstTes.isLeft());
- ComponentInstance value2 = computeInstTes.left().value();
-
- RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
- relationPair.setRequirement(requirement);
-
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), relationPair);
-
- assertTrue("check relation was not created", connectResourcesInService.isRight());
- assertEquals("check error code after connect resource instances failed", titanOperationStatus, connectResourcesInService.right().value());
-
- List<ComponentInstance> resInstances = new ArrayList<ComponentInstance>();
- resInstances.add(value1);
-
- return resInstances;
-
- }
-
- private List<ComponentInstance> buildServiceAndConnectBetweenResourceInstances(String serviceName, Resource resource, Resource computeComponent, String requirement, boolean ignoreCreatingService, String capabilityId, String requirementId) {
-
- String serviceId = "myservice.1.0";
-
- if (false == ignoreCreatingService) {
- ServiceMetadataData createService = createService(serviceId);
- }
- ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", resource.getName());
-
- ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2", computeComponent.getName());
-
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
- assertTrue("check instance added to service", myinstanceRes.isLeft());
- ComponentInstance value1 = myinstanceRes.left().value();
- Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, NodeTypeEnum.Resource, false);
- assertTrue("check instance added to service", computeInstTes.isLeft());
- ComponentInstance value2 = computeInstTes.left().value();
- RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
- relationPair.setRequirement(requirement);
-
- relationPair.setCapabilityUid(capabilityId);
- relationPair.setRequirementUid(requirementId);
- relationPair.setRequirementOwnerId(value1.getUniqueId());
- relationPair.setCapabilityOwnerId(value2.getUniqueId());
-
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), relationPair);
-
- assertTrue("check relation created", connectResourcesInService.isLeft());
-
- List<ComponentInstance> resInstances = new ArrayList<ComponentInstance>();
- resInstances.add(value1);
- resInstances.add(value2);
-
- return resInstances;
-
- }
-
- @Test
- @Ignore
- public void getAllResourceInstancesThree() {
-
- PrintGraph printGraph1 = new PrintGraph();
- int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value());
- try {
-
- Set<String> vertexSetBeforeMethod = printGraph1.getVerticesSet(titanDao.getGraph().left().value());
-
- String capabilityTypeName = CAPABILITY_2;
- String reqName = "host";
- String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER;
- String rootName = "Root2" + TEST_CLASS_NUMBER;
- String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER;
- String computeNodeName = reqNodeName;
- String myResourceVersion = "4.0" + TEST_CLASS_NUMBER;
- String reqRelationship = "myrelationship";
-
- // Create Capability type
- CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
- capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName);
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- // create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
-
- String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
- log.debug(rootResourceJson);
-
- // create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
-
- resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- // create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
-
- // rollbackAndPrint();
-
- // Add capabilities to Compute Resource
- CapabilityDefinition capability = addCapabilityToResource(capabilityTypeName, "host", computeComponent);
-
- // create requirement definition
-
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent);
-
- String parentReqUniqId = addRequirementToResource.left().value().getUniqueId();
-
- // create my resource derived from software component
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true);
-
- String serviceId = "myservice.1.0";
-
- ServiceMetadataData createService = createService(serviceId);
-
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource,
- true);
- assertTrue("check NOT_FOUND is returned", allResourceInstances.isRight());
- assertEquals("check NOT_FOUND is returned", allResourceInstances.right().value(), StorageOperationStatus.NOT_FOUND);
-
- ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", "my-resource");
- myresourceInstance.setName("my-resource");
-
- ComponentInstance computeInstance1 = buildResourceInstance(computeComponent.getUniqueId(), "2", "tosca.nodes.Compute2");
-
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
- assertTrue("check instance added to service", myinstanceRes.isLeft());
- ComponentInstance value1 = myinstanceRes.left().value();
-
- allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, true);
- assertTrue("check resource instances found", allResourceInstances.isLeft());
- ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>> immutablePair = allResourceInstances.left().value();
- List<ComponentInstance> nodes = immutablePair.getKey();
- List<RequirementCapabilityRelDef> edges = immutablePair.getValue();
-
- assertEquals("check resource instances size", 1, nodes.size());
- assertEquals("check resource instances size", 0, edges.size());
-
- Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance1, NodeTypeEnum.Resource, false);
- assertTrue("check instance added to service", computeInstTes.isLeft());
- ComponentInstance value2 = computeInstTes.left().value();
-
- allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, true);
- assertTrue("check resource instances found", allResourceInstances.isLeft());
- immutablePair = allResourceInstances.left().value();
- nodes = immutablePair.getKey();
- edges = immutablePair.getValue();
-
- assertEquals("check resource instances size", 2, nodes.size());
- assertEquals("check resource instances size", 0, edges.size());
-
- String requirement = "host";
- RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
- relationPair.setRequirement(requirement);
- relationPair.setCapabilityUid(capability.getUniqueId());
- relationPair.setRequirementUid(addRequirementToResource.left().value().getUniqueId());
- relationPair.setRequirementOwnerId(value1.getUniqueId());
- relationPair.setCapabilityOwnerId(value2.getUniqueId());
-
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), relationPair);
-
- assertTrue("check relation created", connectResourcesInService.isLeft());
-
- allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, true);
- assertTrue("check resource instances found", allResourceInstances.isLeft());
- immutablePair = allResourceInstances.left().value();
- nodes = immutablePair.getKey();
- edges = immutablePair.getValue();
-
- assertEquals("check resource instances size", 2, nodes.size());
- assertEquals("check resource instances size", 1, edges.size());
-
- List<ComponentInstance> resInstances2 = new ArrayList<ComponentInstance>();
- resInstances2.add(value1);
- resInstances2.add(value2);
-
- ComponentInstance myresourceInstance2 = buildResourceInstance(resource.getUniqueId(), "1", "myresource2");
-
- Either<ComponentInstance, TitanOperationStatus> newResource = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "3", true, myresourceInstance2, NodeTypeEnum.Resource, false);
-
- assertTrue("added resource instance successfully", newResource.isLeft());
-
- relationPair.setRequirement(requirement);
- relationPair.setRequirementOwnerId(newResource.left().value().getUniqueId());
-
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService2 = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, newResource.left().value().getUniqueId(), value2.getUniqueId(),
- relationPair);
- assertTrue("check resource instance was added to service", connectResourcesInService2.isLeft());
-
- allResourceInstances = resourceInstanceOperation.getAllComponentInstances(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource, true);
- assertTrue("check resource instances found", allResourceInstances.isLeft());
- immutablePair = allResourceInstances.left().value();
- nodes = immutablePair.getKey();
- edges = immutablePair.getValue();
-
- assertEquals("check resource instances size", 3, nodes.size());
- assertEquals("check resource instances size", 2, edges.size());
-
- Either<List<ComponentInstance>, TitanOperationStatus> deleteAllResourceInstancesOfService = resourceInstanceOperation.deleteAllComponentInstancesInternal(serviceId, NodeTypeEnum.Service);
- assertTrue("check resource instances was deleted.", deleteAllResourceInstancesOfService.isLeft());
- assertEquals("check number of deleted resource instances.", 3, deleteAllResourceInstancesOfService.left().value().size());
-
- Either<List<RelationshipInstData>, TitanOperationStatus> allRelatinshipInst = titanDao.getAll(NodeTypeEnum.RelationshipInst, RelationshipInstData.class);
- assertTrue("allRelatinshipInst is empty", allRelatinshipInst.isRight());
- assertEquals("allRelatinshipInst result is NOT_FOUND", TitanOperationStatus.NOT_FOUND, allRelatinshipInst.right().value());
-
- Either<Resource, StorageOperationStatus> deleteComputeResource = resourceOperation.deleteResource(computeComponent.getUniqueId(), true);
- assertTrue("delete compute resource succeed", deleteComputeResource.isLeft());
-
- Either<Resource, StorageOperationStatus> deleteSCResource = resourceOperation.deleteResource(softwareComponent.getUniqueId(), true);
- assertTrue("delete software component resource succeed", deleteSCResource.isLeft());
-
- Either<Resource, StorageOperationStatus> deleteMyResource = resourceOperation.deleteResource(resource.getUniqueId(), true);
- assertTrue("delete my resource succeed", deleteMyResource.isLeft());
-
- Either<Resource, StorageOperationStatus> rootResourceDeleted = resourceOperation.deleteResource(rootResource.getUniqueId(), true);
- assertTrue("delete root resource succeed", rootResourceDeleted.isLeft());
-
- Set<String> vertexSetAfterDelete = printGraph1.getVerticesSet(titanDao.getGraph().left().value());
-
- vertexSetAfterDelete.removeAll(vertexSetBeforeMethod);
-
- log.debug("vertexSetAfterDelete={}", vertexSetAfterDelete);
- log.debug("vertexSetAfterDelete size={}", vertexSetAfterDelete.size());
-
- // int numberOfVerticesAfterOperation =
- // printGraph1.getNumberOfVertices(titanDao.getGraph().left().value());
- // System.out.println(numberOfVerticesAfterOperation);
- // 6 - service, 2 tags, capability + 2 parameters
- // compareGraphSize(numberOfVertices + 6, vertexSetBeforeMethod);
-
- } finally {
- rollbackAndPrint(false);
- compareGraphSize(numberOfVertices);
- // printGraph1.printGraphVertices(titanDao.getGraph().left().value());
- }
-
- }
-
- public void testCreateRootResource() {
-
- String name = "tosca.nodes.Root";
-
- String state = LifecycleStateEnum.CERTIFIED.name();
-
- ResourceMetadataData resourceData1 = new ResourceMetadataData();
- resourceData1.getMetadataDataDefinition().setUniqueId(UniqueIdBuilder.buildResourceUniqueId());
- resourceData1.getMetadataDataDefinition().setName(name);
- resourceData1.getMetadataDataDefinition().setState(state);
- resourceData1.getMetadataDataDefinition().setHighestVersion(true);
- resourceData1.getMetadataDataDefinition().setContactId("contactId");
- Either<ResourceMetadataData, TitanOperationStatus> createNode1 = titanDao.createNode(resourceData1, ResourceMetadataData.class);
-
- log.debug("{}", createNode1);
-
- titanDao.commit();
- }
-
- public void testMultiResourceCertified() {
- boolean create = true;
- String name = "myresource7";
- if (create) {
-
- String state = LifecycleStateEnum.CERTIFIED.name();
- boolean isHighestVersion = true;
-
- ResourceMetadataData resourceData1 = new ResourceMetadataData();
- resourceData1.getMetadataDataDefinition().setUniqueId(name + "." + "1.0");
- resourceData1.getMetadataDataDefinition().setName(name);
- resourceData1.getMetadataDataDefinition().setState(state);
- resourceData1.getMetadataDataDefinition().setHighestVersion(true);
- resourceData1.getMetadataDataDefinition().setContactId("contactId");
- Either<ResourceMetadataData, TitanOperationStatus> createNode1 = titanDao.createNode(resourceData1, ResourceMetadataData.class);
-
- log.debug("{}", createNode1);
-
- titanDao.commit();
-
- // resourceData1.setUniqueId(name + "." + "2.0");
- // resourceData1.setHighestVersion(true);
- // resourceData1.setContactId("contactId");
- //
- // Either<ResourceData, TitanOperationStatus> createNode2 = titanDao
- // .createNode(resourceData1, ResourceData.class);
- // System.out.println(createNode2);
- //
- // titanDao.commit();
-
- // resourceData1.setHighestVersion(false);
- resourceData1.getMetadataDataDefinition().setContactId("222contactId222");
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData1, ResourceMetadataData.class);
-
- titanDao.commit();
-
- // TitanGraph titanGraph = titanDao.getGraph().left().value();
- // Iterable<Result<Vertex>> vertices =
- // titanGraph.indexQuery("highestVersion",
- // "v.highestVersion:true").vertices();
- // for (Result<Vertex> vertex : vertices) {
- // Vertex element = vertex.getElement();
- // System.out.println( ElementHelper.getProperties(element));
- // }
-
- }
-
- Either<List<ResourceMetadataData>, TitanOperationStatus> byCriteria = searchForResource(name);
-
- log.debug("{}", byCriteria.left().value().size());
-
- byCriteria = searchForResource(name);
-
- log.debug("{}", byCriteria.left().value().size());
-
- }
-
- private Either<List<ResourceMetadataData>, TitanOperationStatus> searchForResource(String name) {
- Map<String, Object> propertiesToMatch = new HashMap<String, Object>();
- propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
- // propertiesToMatch.put(GraphPropertiesDictionary.IS_ABSTRACT.getProperty(),
- // true);
- propertiesToMatch.put(GraphPropertiesDictionary.NAME.getProperty(), name);
- propertiesToMatch.put(GraphPropertiesDictionary.CONTACT_ID.getProperty(), "contactId");
- // propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(),
- // true);
- Either<List<ResourceMetadataData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class);
- return byCriteria;
- }
-
- @Test
- public void testCreateResourceInstanceTwice() {
-
- PrintGraph printGraph1 = new PrintGraph();
- int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value());
- try {
-
- String capabilityTypeName = CAPABILITY_2;
- String reqName = "host";
- String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER;
- String rootName = "Root2" + TEST_CLASS_NUMBER;
- String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER;
- String computeNodeName = reqNodeName;
- String myResourceVersion = "4.0" + TEST_CLASS_NUMBER;
- String reqRelationship = "myrelationship";
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- // create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
-
- // create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
-
- resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- ComponentInstance myresourceInstance = buildResourceInstance(softwareComponent.getUniqueId(), "1", softwareCompName);
-
- String serviceName = "myservice.1.0";
- ServiceMetadataData createService = createService(serviceName);
- Either<ComponentInstance, StorageOperationStatus> myinstanceRes1 = resourceInstanceOperation.createComponentInstance(serviceName, NodeTypeEnum.Service, "1", myresourceInstance, NodeTypeEnum.Resource, true);
- assertTrue("check resource instance was created", myinstanceRes1.isLeft());
-
- Either<ComponentInstance, StorageOperationStatus> myinstanceRes2 = resourceInstanceOperation.createComponentInstance(serviceName, NodeTypeEnum.Service, "1", myresourceInstance, NodeTypeEnum.Resource, true);
- assertTrue("check resource instance was not created", myinstanceRes2.isRight());
- assertEquals("check error code", StorageOperationStatus.SCHEMA_VIOLATION, myinstanceRes2.right().value());
-
- Either<ComponentInstance, StorageOperationStatus> deleteResourceInstance = resourceInstanceOperation.deleteComponentInstance(NodeTypeEnum.Service, serviceName, myinstanceRes1.left().value().getUniqueId(), true);
- assertTrue("check resource instance was deleted", deleteResourceInstance.isLeft());
-
- deleteResourceInstance = resourceInstanceOperation.deleteComponentInstance(NodeTypeEnum.Service, serviceName, myinstanceRes1.left().value().getUniqueId(), true);
- assertTrue("check resource instance was not deleted", deleteResourceInstance.isRight());
- assertEquals("check resource instance was not deleted", StorageOperationStatus.NOT_FOUND, deleteResourceInstance.right().value());
-
- } finally {
- rollbackAndPrint(false);
- compareGraphSize(numberOfVertices);
- }
-
- }
-
- @Test
- @Ignore
- public void testConnectResourceInstancesTwice() {
-
- PrintGraph printGraph1 = new PrintGraph();
- int numberOfVertices = printGraph1.getNumberOfVertices(titanDao.getGraph().left().value());
-
- try {
-
- String capabilityTypeName1 = CAPABILITY_1;
- String capabilityTypeName2 = CAPABILITY_2;
- String reqName1 = "host1";
- String reqName2 = "host2";
- String reqNodeName = "tosca.nodes.Compute2" + TEST_CLASS_NUMBER;
- String rootName = "Root2" + TEST_CLASS_NUMBER;
- String softwareCompName = "tosca.nodes.SoftwareComponent2" + TEST_CLASS_NUMBER;
- String computeNodeName = reqNodeName;
- String myResourceVersion = "4.0" + TEST_CLASS_NUMBER;
- String reqRelationship = "myrelationship";
-
- // Create Capability type
- CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
- capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef1 = capabilityTypeOperationTest.createCapability(capabilityTypeName1);
- CapabilityTypeDefinition createCapabilityDef2 = capabilityTypeOperationTest.createCapability(capabilityTypeName2);
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- // create root resource
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
-
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
-
- String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
- log.debug(rootResourceJson);
-
- // create software component
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
-
- resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- // create compute component
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
-
- // Add capabilities to Compute Resource
- CapabilityDefinition capabilty1 = addCapabilityToResource(capabilityTypeName1, reqName1, computeComponent);
- CapabilityDefinition capabilty2 = addCapabilityToResource(capabilityTypeName2, reqName2, computeComponent);
-
- // rollbackAndPrint();
-
- // create requirement definition
-
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(capabilityTypeName1, reqName1, reqNodeName, reqRelationship, softwareComponent);
-
- String parentReqUniqId = addRequirementToResource.left().value().getUniqueId();
-
- // create my resource derived from software component
- Resource resource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, "my-resource", myResourceVersion, softwareComponent.getName(), true, true);
-
- String serviceId = "myservice.1.0";
-
- ServiceMetadataData createService = createService(serviceId);
- ComponentInstance myresourceInstance = buildResourceInstance(resource.getUniqueId(), "1", "my-resource");
-
- ComponentInstance computeInstance = buildResourceInstance(computeComponent.getUniqueId(), "2", computeNodeName);
-
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
- assertTrue("check instance added to service", myinstanceRes.isLeft());
- ComponentInstance value1 = myinstanceRes.left().value();
- Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, NodeTypeEnum.Resource, false);
- assertTrue("check instance added to service", computeInstTes.isLeft());
- ComponentInstance value2 = computeInstTes.left().value();
-
- RequirementCapabilityRelDef relation = new RequirementCapabilityRelDef();
- String fromResUid = value1.getUniqueId();
- String toResUid = value2.getUniqueId();
- relation.setFromNode(fromResUid);
- relation.setToNode(toResUid);
- List<RequirementAndRelationshipPair> relationships = new ArrayList<RequirementAndRelationshipPair>();
- RequirementAndRelationshipPair immutablePair1 = new RequirementAndRelationshipPair(reqName1, null);
- immutablePair1.setCapabilityUid(capabilty1.getUniqueId());
- immutablePair1.setRequirementUid(parentReqUniqId);
- immutablePair1.setRequirementOwnerId(fromResUid);
- immutablePair1.setCapabilityOwnerId(toResUid);
- relationships.add(immutablePair1);
-
- relation.setRelationships(relationships);
-
- Either<RequirementCapabilityRelDef, StorageOperationStatus> connectResourcesInService = resourceInstanceOperation.associateResourceInstances(serviceId, NodeTypeEnum.Service, relation, true, false);
- assertTrue("check association succeed", connectResourcesInService.isLeft());
-
- relationships.clear();
- RequirementAndRelationshipPair immutablePair2 = new RequirementAndRelationshipPair(reqName2, null);
- immutablePair2.setCapabilityUid(capabilty2.getUniqueId());
- immutablePair2.setRequirementUid(parentReqUniqId);
- relationships.add(immutablePair2);
-
- RequirementCapabilityRelDef firstRelation = connectResourcesInService.left().value();
- connectResourcesInService = resourceInstanceOperation.associateResourceInstances(serviceId, NodeTypeEnum.Service, relation, true, false);
- assertTrue("check association succeed", connectResourcesInService.isRight());
- assertEquals("check association failed", StorageOperationStatus.MATCH_NOT_FOUND, connectResourcesInService.right().value());
-
- Either<RequirementCapabilityRelDef, StorageOperationStatus> disconnectResourcesInService = resourceInstanceOperation.dissociateResourceInstances(serviceId, NodeTypeEnum.Service, firstRelation, true);
-
- assertTrue("check dissociation succeed", disconnectResourcesInService.isLeft());
-
- disconnectResourcesInService = resourceInstanceOperation.dissociateResourceInstances(serviceId, NodeTypeEnum.Service, relation, true);
-
- assertTrue("check dissociation failed", disconnectResourcesInService.isRight());
- assertEquals("check association failed", StorageOperationStatus.NOT_FOUND, disconnectResourcesInService.right().value());
- } finally {
- rollbackAndPrint();
- compareGraphSize(numberOfVertices);
- }
-
- }
-
- private Resource createComputeWithCapability(String capabilityTypeName, String computeNodeName, ResourceOperationTest resourceOperationTest, Resource rootResource) {
- // create compute component
- // String id = UniqueIdBuilder.buildResourceUniqueId(computeNodeName,
- // "1.0");
- // if (resourceOperation.getResource(id).isLeft()){
- // resourceOperation.deleteResource(id);
- // }
- Either<List<Resource>, StorageOperationStatus> oldResource = resourceOperation.getResourceByNameAndVersion(computeNodeName, "1.0", false);
- if (oldResource.isLeft()) {
- for (Resource old : oldResource.left().value()) {
- if (old.getResourceType().equals(ResourceTypeEnum.VFC)) {
- resourceOperation.deleteResource(old.getUniqueId());
- }
- }
-
- }
-
- Resource computeComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, computeNodeName, "1.0", rootResource.getName(), true, true);
-
- // rollbackAndPrint();
-
- // Add capabilities to Compute Resource
- addCapabilityToResource(capabilityTypeName, "host", computeComponent);
- return resourceOperation.getResource(computeComponent.getUniqueId()).left().value();
- }
-
- private Resource createSoftwareComponentWithReq(String softwareCompName, ResourceOperationTest resourceOperationTest, Resource rootResource, String capabilityTypeName, String reqName, String reqRelationship, String reqNodeName) {
- Either<ResourceMetadataData, TitanOperationStatus> updateNode;
- ResourceMetadataData resourceData = new ResourceMetadataData();
- // create software component
- // String id = UniqueIdBuilder.buildResourceUniqueId(softwareCompName,
- // "1.0");
- // if (resourceOperation.getResource(id).isLeft()){
- // resourceOperation.deleteResource(id);
- // }
- Either<List<Resource>, StorageOperationStatus> oldResource = resourceOperation.getResourceByNameAndVersion(softwareCompName, "1.0", false);
- if (oldResource.isLeft()) {
- if (oldResource.isLeft()) {
- for (Resource old : oldResource.left().value()) {
- if (old.getResourceType().equals(ResourceTypeEnum.VFC)) {
- resourceOperation.deleteResource(old.getUniqueId());
- }
- }
-
- }
- }
-
- Resource softwareComponent = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, softwareCompName, "1.0", rootResource.getName(), true, true);
-
- resourceData.getMetadataDataDefinition().setUniqueId(softwareComponent.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource = addRequirementToResource(capabilityTypeName, reqName, reqNodeName, reqRelationship, softwareComponent);
-
- String parentReqUniqId = addRequirementToResource.left().value().getUniqueId();
-
- return resourceOperation.getResource(softwareComponent.getUniqueId()).left().value();
- }
-
- private Resource createRootResource(String rootName, ResourceOperationTest resourceOperationTest) {
- // create root resource
- // String rootId = UniqueIdBuilder.buildResourceUniqueId(rootName,
- // "1.0");
- Either<List<Resource>, StorageOperationStatus> oldResource = resourceOperation.getResourceByNameAndVersion(rootName, "1.0", false);
- if (oldResource.isLeft()) {
- for (Resource old : oldResource.left().value()) {
- if (old.getResourceType().equals(ResourceTypeEnum.VFC)) {
- resourceOperation.deleteResource(old.getUniqueId());
- }
- }
-
- }
- Resource rootResource = resourceOperationTest.createResource(USER_ID, CATEGORY_NAME, rootName, "1.0", null, true, true);
- ResourceMetadataData rootResourceData = new ResourceMetadataData();
- rootResourceData.getMetadataDataDefinition().setUniqueId(rootResource.getUniqueId());
- rootResourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(rootResourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- Either<Resource, StorageOperationStatus> fetchRootResource = resourceOperation.getResource(rootResource.getUniqueId(), true);
-
- String rootResourceJson = prettyGson.toJson(fetchRootResource.left().value());
- log.debug(rootResourceJson);
- return rootResource;
- }
-
- public void addResourceInstancesAndRelation(String serviceId) {
-
- String rootName = "tosca.nodes.test.root";
- String softwareCompName = "tosca.nodes.test.softwarecomponent";
- String capabilityTypeName = "myCapability";
- String reqName = "host";
- String computeNodeName = "tosca.nodes.test.compute";
- String reqRelationship = "myRelationship";
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- Resource rootResource = createRootResource(rootName, resourceOperationTest);
- // Create Capability type
- CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
- capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- CapabilityTypeDefinition createCapabilityDef = capabilityTypeOperationTest.createCapability(capabilityTypeName);
-
- Resource softwareComponentResource = createSoftwareComponentWithReq(softwareCompName, resourceOperationTest, rootResource, capabilityTypeName, reqName, reqRelationship, computeNodeName);
- Resource compute = createComputeWithCapability(capabilityTypeName, computeNodeName, resourceOperationTest, rootResource);
-
- // resource1
- ComponentInstance myresourceInstance = buildResourceInstance(softwareComponentResource.getUniqueId(), "1", "tosca.nodes.test.root");
-
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
-
- assertTrue("check instance added to service", myinstanceRes.isLeft());
-
- // resource2
- ComponentInstance computeInstance = buildResourceInstance(compute.getUniqueId(), "2", "tosca.nodes.test.compute");
- ComponentInstance value1 = myinstanceRes.left().value();
-
- Either<ComponentInstance, TitanOperationStatus> computeInstTes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "2", true, computeInstance, NodeTypeEnum.Resource, false);
- assertTrue("check instance added to service", computeInstTes.isLeft());
- ComponentInstance value2 = computeInstTes.left().value();
-
- RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
- relationPair.setRequirement(reqName);
- relationPair.setCapability(capabilityTypeName);
-
- String capId = "";
- Map<String, List<CapabilityDefinition>> capabilities = compute.getCapabilities();
- for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) {
- capId = entry.getValue().get(0).getUniqueId();
- }
- relationPair.setCapabilityUid(capId);
- Map<String, List<RequirementDefinition>> requirements = softwareComponentResource.getRequirements();
- String reqId = "";
- for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) {
- reqId = entry.getValue().get(0).getUniqueId();
- }
- relationPair.setRequirementUid(reqId);
- relationPair.setRequirementOwnerId(value1.getUniqueId());
- relationPair.setCapabilityOwnerId(value2.getUniqueId());
- relationPair.setCapabilityUid(capId);
-
- Either<RelationshipInstData, TitanOperationStatus> connectResourcesInService = resourceInstanceOperation.connectResourcesInService(serviceId, NodeTypeEnum.Service, value1.getUniqueId(), value2.getUniqueId(), relationPair);
-
- assertTrue("check relation created", connectResourcesInService.isLeft());
-
- }
-
- @Test
- @Ignore
- public void addResourceInstancesResourceDeleted() {
-
- String rootName = "tosca.nodes.test.root";
- String softwareCompName = "tosca.nodes.test.softwarecomponent";
- String capabilityTypeName = "myCapability";
- String reqName = "host";
- String computeNodeName = "tosca.nodes.test.compute";
- String reqRelationship = "myRelationship";
-
- ServiceMetadataData origService = createService("myService");
- String serviceId = (String) origService.getUniqueId();
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- Resource rootResource = createRootResource(rootName, resourceOperationTest);
- // Create Capability type
- CapabilityTypeOperationTest capabilityTypeOperationTest = new CapabilityTypeOperationTest();
- capabilityTypeOperationTest.setOperations(titanDao, capabilityTypeOperation);
- capabilityTypeOperationTest.createCapability(capabilityTypeName);
-
- Resource softwareComponentResource = createSoftwareComponentWithReq(softwareCompName, resourceOperationTest, rootResource, capabilityTypeName, reqName, reqRelationship, computeNodeName);
-
- deleteResource(softwareComponentResource.getUniqueId());
-
- // resource1
- ComponentInstance myresourceInstance = buildResourceInstance(softwareComponentResource.getUniqueId(), "1", "tosca.nodes.test.root");
-
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
-
- assertTrue("check instance not added to service", myinstanceRes.isRight());
-
- }
-
- @Test
- @Ignore
- public void testDeploymentArtifactsOnRI() {
-
- String rootName = "tosca.nodes.test.root";
-
- ServiceMetadataData origService = createService("testDeploymentArtifactsOnRI");
- String serviceId = (String) origService.getUniqueId();
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- Resource rootResource = createRootResource(rootName, resourceOperationTest);
- ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(), "myArtifact");
-
- // resource1
- ComponentInstance myresourceInstance = buildResourceInstance(rootResource.getUniqueId(), "1", rootName);
-
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
-
- assertTrue("check instance added to service", myinstanceRes.isLeft());
-
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service,
- NodeTypeEnum.Resource);
- assertTrue(resourceInstancesOfService.isLeft());
- List<ComponentInstance> resourceInstanceList = resourceInstancesOfService.left().value().left;
- assertTrue(resourceInstanceList.size() == 1);
- ComponentInstance resourceInstance = resourceInstanceList.get(0);
- assertTrue(resourceInstance.getDeploymentArtifacts().size() == 1);
- Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
- assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel()));
-
- ArtifactDefinition heatEnvArtifact = new ArtifactDefinition(addArtifactToResource);
- heatEnvArtifact.setArtifactType("HEAT_ENV");
- heatEnvArtifact.setArtifactLabel(addArtifactToResource.getArtifactLabel() + "env");
- heatEnvArtifact.setUniqueId(null);
-
- Either<ArtifactDefinition, StorageOperationStatus> either = artifactOperation.addHeatEnvArtifact(heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true);
- assertTrue(either.isLeft());
-
- resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource);
- assertTrue(resourceInstancesOfService.isLeft());
- resourceInstanceList = resourceInstancesOfService.left().value().left;
- assertTrue(resourceInstanceList.size() == 1);
- resourceInstance = resourceInstanceList.get(0);
- assertTrue(resourceInstance.getDeploymentArtifacts().size() == 2);
- artifacts = resourceInstance.getDeploymentArtifacts();
- assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel()));
- assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel() + "env"));
- ArtifactDefinition heatEnvFromRI = artifacts.get(addArtifactToResource.getArtifactLabel() + "env");
- assertEquals(addArtifactToResource.getUniqueId(), heatEnvFromRI.getGeneratedFromId());
-
- List<HeatParameterDefinition> heatParameters = artifacts.get(addArtifactToResource.getArtifactLabel()).getListHeatParameters();
- assertNotNull(heatParameters);
- assertTrue(heatParameters.size() == 1);
-
- List<HeatParameterDefinition> heatEnvParameters = heatEnvFromRI.getListHeatParameters();
- assertNotNull(heatEnvParameters);
- assertTrue(heatEnvParameters.size() == 1);
-
- resourceOperation.deleteResource(rootResource.getUniqueId());
-
- }
-
- @Test
- @Ignore
- public void deleteResourceInstanceWithArtifacts() {
- String rootName = "tosca.nodes.test.root";
-
- ServiceMetadataData origService = createService("deleteResourceInstanceWithArtifacts");
- String serviceId = (String) origService.getUniqueId();
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- Resource rootResource = createRootResource(rootName, resourceOperationTest);
- ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(), "myArtifact");
-
- // resource1
- ComponentInstance myresourceInstance = buildResourceInstance(rootResource.getUniqueId(), "1", rootName);
-
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
-
- ArtifactDefinition heatEnvArtifact = new ArtifactDefinition(addArtifactToResource);
- heatEnvArtifact.setArtifactType("HEAT_ENV");
- heatEnvArtifact.setArtifactLabel(addArtifactToResource.getArtifactLabel() + "env");
- heatEnvArtifact.setUniqueId(null);
-
- assertTrue("check instance added to service", myinstanceRes.isLeft());
-
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service,
- NodeTypeEnum.Resource);
- assertTrue(resourceInstancesOfService.isLeft());
- List<ComponentInstance> resourceInstanceList = resourceInstancesOfService.left().value().left;
- assertTrue(resourceInstanceList.size() == 1);
- ComponentInstance resourceInstance = resourceInstanceList.get(0);
-
- Either<ArtifactDefinition, StorageOperationStatus> either = artifactOperation.addHeatEnvArtifact(heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true);
- assertTrue(either.isLeft());
- ArtifactDefinition heatEnvDefinition = either.left().value();
-
- // delete resource instance
- Either<ComponentInstance, StorageOperationStatus> deleteResourceInstance = resourceInstanceOperation.deleteComponentInstance(NodeTypeEnum.Service, serviceId, resourceInstance.getUniqueId());
- assertTrue(deleteResourceInstance.isLeft());
-
- // check heat env deleted
- ArtifactData artifactData = new ArtifactData();
- Either<ArtifactData, TitanOperationStatus> getDeletedArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), heatEnvDefinition.getUniqueId(), ArtifactData.class);
- assertTrue(getDeletedArtifact.isRight());
-
- // check heat is not deleted
- getDeletedArtifact = titanDao.getNode(artifactData.getUniqueIdKey(), addArtifactToResource.getUniqueId(), ArtifactData.class);
- assertTrue(getDeletedArtifact.isLeft());
-
- HeatParameterData heatParamData = new HeatParameterData();
- Either<HeatParameterData, TitanOperationStatus> heatParamNode = titanDao.getNode(heatParamData.getUniqueIdKey(), addArtifactToResource.getHeatParameters().get(0).getUniqueId(), HeatParameterData.class);
- assertTrue(heatParamNode.isLeft());
-
- resourceOperation.deleteResource(rootResource.getUniqueId());
-
- }
-
- @Test
- @Ignore
- public void getHeatEnvParams() {
- String rootName = "tosca.nodes.test.root";
-
- ServiceMetadataData origService = createService("getHeatEnvParams");
- String serviceId = (String) origService.getUniqueId();
-
- ResourceOperationTest resourceOperationTest = new ResourceOperationTest();
- resourceOperationTest.setOperations(titanDao, resourceOperation, propertyOperation);
-
- Resource rootResource = createRootResource(rootName, resourceOperationTest);
- ArtifactDefinition addArtifactToResource = addArtifactToResource(USER_ID, rootResource.getUniqueId(), "myArtifact");
-
- // resource1
- ComponentInstance myresourceInstance = buildResourceInstance(rootResource.getUniqueId(), "1", rootName);
-
- Either<ComponentInstance, TitanOperationStatus> myinstanceRes = resourceInstanceOperation.addComponentInstanceToContainerComponent(serviceId, NodeTypeEnum.Service, "1", true, myresourceInstance, NodeTypeEnum.Resource, false);
-
- ArtifactDefinition heatEnvArtifact = new ArtifactDefinition(addArtifactToResource);
- heatEnvArtifact.setArtifactType("HEAT_ENV");
- heatEnvArtifact.setArtifactLabel(addArtifactToResource.getArtifactLabel() + "env");
- heatEnvArtifact.setUniqueId(null);
-
- assertTrue("check instance added to service", myinstanceRes.isLeft());
-
- Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, TitanOperationStatus> resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service,
- NodeTypeEnum.Resource);
- assertTrue(resourceInstancesOfService.isLeft());
- List<ComponentInstance> resourceInstanceList = resourceInstancesOfService.left().value().left;
- assertTrue(resourceInstanceList.size() == 1);
- ComponentInstance resourceInstance = resourceInstanceList.get(0);
-
- Either<ArtifactDefinition, StorageOperationStatus> either = artifactOperation.addHeatEnvArtifact(heatEnvArtifact, addArtifactToResource, resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true);
- assertTrue(either.isLeft());
- ArtifactDefinition heatEnvDefinition = either.left().value();
-
- // update value
- String newHeatValue = "123";
- addHeatValueToEnv(heatEnvDefinition.getUniqueId(), addArtifactToResource.getListHeatParameters().get(0), newHeatValue);
-
- // check values received
-
- resourceInstancesOfService = resourceInstanceOperation.getComponentInstancesOfComponent(serviceId, NodeTypeEnum.Service, NodeTypeEnum.Resource);
- assertTrue(resourceInstancesOfService.isLeft());
- resourceInstanceList = resourceInstancesOfService.left().value().left;
- assertTrue(resourceInstanceList.size() == 1);
- resourceInstance = resourceInstanceList.get(0);
- assertTrue(resourceInstance.getDeploymentArtifacts().size() == 2);
- Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
- assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel()));
- assertNotNull(artifacts.get(addArtifactToResource.getArtifactLabel() + "env"));
-
- List<HeatParameterDefinition> heatParameters = artifacts.get(addArtifactToResource.getArtifactLabel()).getListHeatParameters();
- assertNotNull(heatParameters);
- assertTrue(heatParameters.size() == 1);
- HeatParameterDefinition heatParameterTemplate = heatParameters.get(0);
-
- List<HeatParameterDefinition> heatEnvParameters = artifacts.get(addArtifactToResource.getArtifactLabel() + "env").getListHeatParameters();
- assertNotNull(heatEnvParameters);
- assertTrue(heatEnvParameters.size() == 1);
- HeatParameterDefinition heatParameterEnv = heatEnvParameters.get(0);
-
- assertEquals(heatParameterEnv.getDefaultValue(), heatParameterTemplate.getCurrentValue());
- assertEquals(newHeatValue, heatParameterEnv.getCurrentValue());
- assertFalse(newHeatValue.equals(heatParameterTemplate.getCurrentValue()));
-
- resourceOperation.deleteResource(rootResource.getUniqueId());
-
- }
-
- public void addHeatValueToEnv(String artifactId, HeatParameterDefinition heatDefinition, String value) {
- HeatParameterValueData heatValueData = new HeatParameterValueData();
- heatValueData.setValue(value);
- heatValueData.setUniqueId(artifactId + "." + heatDefinition.getName());
- Either<HeatParameterValueData, TitanOperationStatus> createValue = titanDao.createNode(heatValueData, HeatParameterValueData.class);
- assertTrue(createValue.isLeft());
- HeatParameterValueData value2 = createValue.left().value();
- HeatParameterData heatParamData = new HeatParameterData(heatDefinition);
- Either<GraphRelation, TitanOperationStatus> createRelation = titanDao.createRelation(value2, heatParamData, GraphEdgeLabels.PROPERTY_IMPL, null);
- assertTrue(createRelation.isLeft());
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), heatDefinition.getName());
- Either<GraphRelation, TitanOperationStatus> createRelation2 = titanDao.createRelation(new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId), value2, GraphEdgeLabels.PARAMETER_VALUE, props);
- assertTrue(createRelation2.isLeft());
- titanDao.commit();
-
- }
-
- public static String normaliseComponentName(String name) {
- String[] split = splitComponentName(name);
- StringBuffer sb = new StringBuffer();
- for (String splitElement : split) {
- sb.append(splitElement);
- }
- return sb.toString();
-
- }
-
- private static String[] splitComponentName(String name) {
- String normalizedName = name.toLowerCase();
- normalizedName = COMPONENT_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" ");
- String[] split = normalizedName.split(" ");
- return split;
- }
-
- public static String normaliseComponentInstanceName(String name) {
- String[] split = splitComponentInstanceName(name);
- StringBuffer sb = new StringBuffer();
- for (String splitElement : split) {
- sb.append(splitElement);
- }
- return sb.toString();
-
- }
-
- private static String[] splitComponentInstanceName(String name) {
- String normalizedName = name.toLowerCase();
- normalizedName = COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" ");
- String[] split = normalizedName.split(" ");
- return split;
- }
-
- private ArtifactDefinition addArtifactToResource(String userId, String resourceId, String artifactName) {
- ArtifactDefinition artifactInfo = new ArtifactDefinition();
-
- artifactInfo.setArtifactName(artifactName + ".yml");
- artifactInfo.setArtifactType("HEAT");
- artifactInfo.setDescription("hdkfhskdfgh");
- artifactInfo.setArtifactChecksum("UEsDBAoAAAAIAAeLb0bDQz");
- artifactInfo.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT);
-
- artifactInfo.setUserIdCreator(userId);
- String fullName = "Jim H";
- artifactInfo.setUpdaterFullName(fullName);
- long time = System.currentTimeMillis();
- artifactInfo.setCreatorFullName(fullName);
- artifactInfo.setCreationDate(time);
- artifactInfo.setLastUpdateDate(time);
- artifactInfo.setUserIdLastUpdater(userId);
- artifactInfo.setArtifactLabel(artifactName);
- artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel()));
- artifactInfo.setEsId(artifactInfo.getUniqueId());
-
- List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>();
- HeatParameterDefinition heatParam = new HeatParameterDefinition();
- heatParam.setCurrentValue("11");
- heatParam.setDefaultValue("22");
- heatParam.setDescription("desc");
- heatParam.setName("myParam");
- heatParam.setType("number");
- heatParams.add(heatParam);
- artifactInfo.setListHeatParameters(heatParams);
-
- Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation.addArifactToComponent(artifactInfo, resourceId, NodeTypeEnum.Resource, true, true);
- assertTrue(artifact.isLeft());
- return artifact.left().value();
- }
-}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java
deleted file mode 100644
index efd55d58fb..0000000000
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperationTest.java
+++ /dev/null
@@ -1,953 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.Set;
-import java.util.UUID;
-
-import org.apache.commons.lang3.tuple.ImmutablePair;
-import org.apache.tinkerpop.gremlin.structure.Direction;
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.junit.BeforeClass;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mockito;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.CapabilityDefinition;
-import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.ComponentInstanceProperty;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.ModelTestBase;
-import org.openecomp.sdc.be.model.PropertyConstraint;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil;
-import org.openecomp.sdc.be.model.tosca.ToscaType;
-import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint;
-import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint;
-import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint;
-import org.openecomp.sdc.be.resources.data.PropertyData;
-import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
-import org.openecomp.sdc.be.resources.data.UserData;
-import org.openecomp.sdc.be.resources.data.category.CategoryData;
-import org.openecomp.sdc.be.resources.data.category.SubCategoryData;
-import org.openecomp.sdc.be.unittests.utils.FactoryUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanGraphQuery;
-import com.thinkaurelius.titan.core.TitanVertex;
-import com.thinkaurelius.titan.graphdb.query.graph.GraphCentricQueryBuilder;
-
-import fj.data.Either;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration("classpath:application-context-test.xml")
-public class ResourceOperationTest extends ModelTestBase {
-
- private static Logger log = LoggerFactory.getLogger(ResourceOperationTest.class.getName());
- @javax.annotation.Resource(name = "titan-generic-dao")
- private TitanGenericDao titanDao;
-
- @javax.annotation.Resource(name = "resource-operation")
- private ResourceOperation resourceOperation;
-
- @javax.annotation.Resource(name = "property-operation")
- private PropertyOperation propertyOperation;
-
- @javax.annotation.Resource(name = "lifecycle-operation")
- private LifecycleOperation lifecycleOperation;
-
- @javax.annotation.Resource(name = "capability-operation")
- private CapabilityOperation capabilityOperation;
-
- @javax.annotation.Resource(name = "capability-type-operation")
- private CapabilityTypeOperation capabilityTypeOperation;
-
- private static String CATEGORY_NAME = "category/mycategory";
- private static String CATEGORY_NAME_UPDATED = "category1/updatedcategory";
-
- @BeforeClass
- public static void setupBeforeClass() {
-
- ModelTestBase.init();
- }
-
- public void setOperations(TitanGenericDao titanGenericDao, ResourceOperation resourceOperation, PropertyOperation propertyOperation) {
- this.titanDao = titanGenericDao;
- this.resourceOperation = resourceOperation;
- this.propertyOperation = propertyOperation;
- }
-
- @Test
- public void dummyTest() {
-
- }
-
- private Resource buildResourceMetadata(String userId, String category, String resourceName, String resourceVersion) {
-
- Resource resource = new Resource();
- resource.setName(resourceName);
- resource.setVersion(resourceVersion);
- ;
- resource.setDescription("description 1");
- resource.setAbstract(false);
- resource.setCreatorUserId(userId);
- resource.setContactId("contactId@sdc.com");
- resource.setVendorName("vendor 1");
- resource.setVendorRelease("1.0.0");
- resource.setToscaResourceName(resourceName);
- String[] categoryArr = category.split("/");
- resource.addCategory(categoryArr[0], categoryArr[1]);
- resource.setIcon("images/my.png");
- List<String> tags = new ArrayList<String>();
- tags.add("TAG1");
- tags.add("TAG2");
- resource.setTags(tags);
- return resource;
- }
-
- private UserData deleteAndCreateUser(String userId, String firstName, String lastName) {
- UserData userData = new UserData();
- userData.setUserId(userId);
- userData.setFirstName(firstName);
- userData.setLastName(lastName);
-
- titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class);
- titanDao.createNode(userData, UserData.class);
- titanDao.commit();
-
- return userData;
- }
-
- private void deleteAndCreateCategory(String category) {
- String[] names = category.split("/");
- OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao);
- }
-
- public Resource createResource(String userId, String category, String resourceName, String resourceVersion, String parentResourceName, boolean isAbstract, boolean isHighestVersion) {
-
- String propName1 = "disk_size";
- String propName2 = "num_cpus";
-
- List<String> derivedFrom = new ArrayList<String>();
- if (parentResourceName != null) {
- derivedFrom.add(parentResourceName);
- }
- Resource resource = buildResourceMetadata(userId, category, resourceName, resourceVersion);
-
- resource.setAbstract(isAbstract);
- resource.setHighestVersion(isHighestVersion);
-
- Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>();
-
- PropertyDefinition property1 = new PropertyDefinition();
- property1.setDefaultValue("10");
- property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
- property1.setType(ToscaType.INTEGER.name().toLowerCase());
- List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>();
- GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0");
- log.debug("{}", propertyConstraint1);
-
- constraints.add(propertyConstraint1);
-
- LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10");
- constraints.add(propertyConstraint2);
-
- property1.setConstraints(constraints);
-
- properties.put(propName1, property1);
-
- PropertyDefinition property2 = new PropertyDefinition();
- property2.setDefaultValue("2");
- property2.setDescription("Number of (actual or virtual) CPUs associated with the Compute node.");
- property2.setType(ToscaType.INTEGER.name().toLowerCase());
- List<PropertyConstraint> constraints3 = new ArrayList<PropertyConstraint>();
- List<String> range = new ArrayList<String>();
- range.add("1");
- range.add("4");
-
- InRangeConstraint propertyConstraint3 = new InRangeConstraint(range);
- constraints3.add(propertyConstraint3);
- // property2.setConstraints(constraints3);
- property2.setConstraints(constraints3);
- properties.put(propName2, property2);
-
- resource.setDerivedFrom(derivedFrom);
-
- resource.setProperties(convertMapToList(properties));
-
- Either<Resource, StorageOperationStatus> result = resourceOperation.createResource(resource, true);
-
- assertTrue(result.isLeft());
- Resource resultResource = result.left().value();
-
- // assertEquals("check resource unique id",
- // UniqueIdBuilder.buildResourceUniqueId(resourceName,
- // resourceVersion), resultResource.getUniqueId());
- assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultResource.getLifecycleState());
-
- // retrieve property from graph
- String resourceId = resultResource.getUniqueId();
- // String resourceId = UniqueIdBuilder.buildResourceUniqueId(
- // resource.getResourceName(), resource.getResourceVersion());
-
- Either<PropertyDefinition, StorageOperationStatus> either = propertyOperation.getPropertyOfResource(propName1, resourceId);
-
- assertTrue(either.isLeft());
- PropertyDefinition propertyDefinition = either.left().value();
- assertEquals("check property default value", property1.getDefaultValue(), propertyDefinition.getDefaultValue());
- assertEquals("check property description", property1.getDescription(), propertyDefinition.getDescription());
- assertEquals("check property type", property1.getType(), propertyDefinition.getType());
- assertEquals("check property unique id", property1.getUniqueId(), propertyDefinition.getUniqueId());
- assertEquals("check property consitraints size", property1.getConstraints().size(), propertyDefinition.getConstraints().size());
-
- return resultResource;
-
- }
-
- public Resource createResourceOverrideProperty(String userId, String category, String resourceName, String resourceVersion, String parentResourceName, boolean isAbstract, boolean isHighestVersion) {
-
- String propName1 = "disk_size";
-
- List<String> derivedFrom = new ArrayList<String>();
- if (parentResourceName != null) {
- derivedFrom.add(parentResourceName);
- }
-
- Map<String, PropertyDefinition> properties = new HashMap<String, PropertyDefinition>();
- PropertyDefinition property1 = new PropertyDefinition();
- property1.setDefaultValue("9");
- property1.setDescription("Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node.");
- property1.setType(ToscaType.INTEGER.name().toLowerCase());
- List<PropertyConstraint> constraints = new ArrayList<PropertyConstraint>();
- GreaterThanConstraint propertyConstraint1 = new GreaterThanConstraint("0");
- log.debug("{}", propertyConstraint1);
- constraints.add(propertyConstraint1);
- LessOrEqualConstraint propertyConstraint2 = new LessOrEqualConstraint("10");
- constraints.add(propertyConstraint2);
- property1.setConstraints(constraints);
- properties.put(propName1, property1);
-
- Resource resource = buildResourceMetadata(userId, category, resourceName, resourceVersion);
- resource.setAbstract(isAbstract);
- resource.setHighestVersion(isHighestVersion);
- resource.setDerivedFrom(derivedFrom);
- resource.setProperties(convertMapToList(properties));
-
- Either<Resource, StorageOperationStatus> result = resourceOperation.createResource(resource, true);
-
- assertTrue(result.isLeft());
- Resource resultResource = result.left().value();
-
- // assertEquals("check resource unique id",
- // UniqueIdBuilder.buildResourceUniqueId(resourceName,
- // resourceVersion), resultResource.getUniqueId());
- assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultResource.getLifecycleState());
-
- // retrieve property from graph
- String resourceId = resultResource.getUniqueId();
- // String resourceId = UniqueIdBuilder.buildResourceUniqueId(
- // resource.getResourceName(), resource.getResourceVersion());
-
- Either<PropertyDefinition, StorageOperationStatus> either = propertyOperation.getPropertyOfResource(propName1, resourceId);
-
- assertTrue(either.isLeft());
- PropertyDefinition propertyDefinition = either.left().value();
- assertEquals("check property default value", property1.getDefaultValue(), propertyDefinition.getDefaultValue());
- assertEquals("check property description", property1.getDescription(), propertyDefinition.getDescription());
- assertEquals("check property type", property1.getType(), propertyDefinition.getType());
- assertEquals("check property unique id", property1.getUniqueId(), propertyDefinition.getUniqueId());
- assertEquals("check property consitraints size", property1.getConstraints().size(), propertyDefinition.getConstraints().size());
-
- return resultResource;
- }
-
- public static List<PropertyDefinition> convertMapToList(Map<String, PropertyDefinition> properties) {
- if (properties == null) {
- return null;
- }
-
- List<PropertyDefinition> definitions = new ArrayList<>();
- for (Entry<String, PropertyDefinition> entry : properties.entrySet()) {
- String name = entry.getKey();
- PropertyDefinition propertyDefinition = entry.getValue();
- propertyDefinition.setName(name);
- definitions.add(propertyDefinition);
- }
-
- return definitions;
- }
-
- @Test
- public void testFollowed() {
- String rootName = "Root123";
-
- String userId = "jh0003";
- String category = CATEGORY_NAME;
- deleteAndCreateUser(userId, "first_" + userId, "last_" + userId);
- deleteAndCreateCategory(category);
-
- Resource rootResource = createResource(userId, category, rootName, "1.0", null, false, true);
- log.debug(" *** create **");
- log.debug("{}", rootResource);
- String resourceId = rootResource.getUniqueId();
-
- Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
- lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>();
- lastStateStates.add(LifecycleStateEnum.CERTIFIED);
-
- Either<List<Resource>, StorageOperationStatus> followed = resourceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false);
- assertTrue(followed.isLeft());
- List<Resource> list = followed.left().value();
-
- assertEquals(1, list.size());
- resourceOperation.deleteResource(resourceId);
-
- followed = resourceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false);
- assertTrue(followed.isLeft());
- list = followed.left().value();
- assertTrue(list.isEmpty());
-
- }
-
- @Ignore
- @Test
- public void testGetLatestVersion() {
- String rootName = "Root123";
-
- String userId = "jh0003";
- String category = "category/mycategory";
- deleteAndCreateUser(userId, "first_" + userId, "last_" + userId);
- deleteAndCreateCategory(category);
-
- Either<Resource, StorageOperationStatus> latestByName = resourceOperation.getLatestByName(rootName, true);
- assertTrue(latestByName.isRight());
- assertEquals(StorageOperationStatus.NOT_FOUND, latestByName.right().value());
-
- Resource rootResource = createResource(userId, category, rootName, "1.0", null, false, true);
-
- latestByName = resourceOperation.getLatestByName(rootName, true);
- assertTrue(latestByName.isLeft());
-
- Resource rootResourceHighest = createResource(userId, category, rootName, "1.3", null, false, true);
-
- latestByName = resourceOperation.getLatestByName(rootName, false);
- assertTrue(latestByName.isLeft());
- assertEquals(rootResourceHighest.getUniqueId(), latestByName.left().value().getUniqueId());
-
- resourceOperation.deleteResource(rootResource.getUniqueId());
- resourceOperation.deleteResource(rootResourceHighest.getUniqueId());
- }
-
- @Test
- public void testOverrideResource() {
- String rootName = "Root123";
-
- String userId = "jh0003";
- String category = CATEGORY_NAME;
- String updatedCategory = CATEGORY_NAME_UPDATED;
- deleteAndCreateUser(userId, "first_" + userId, "last_" + userId);
- deleteAndCreateCategory(category);
- deleteAndCreateCategory(updatedCategory);
-
- Resource rootResource = createResource(userId, category, rootName, "1.1", null, false, true);
-
- rootResource.setCategories(null);
- String[] updateArr = updatedCategory.split("/");
- rootResource.addCategory(updateArr[0], updateArr[1]);
- List<PropertyDefinition> properties = rootResource.getProperties();
- PropertyDefinition propertyDefinition = findProperty(properties, "disk_size");
-
- rootResource.setProperties(new ArrayList<PropertyDefinition>());
- propertyDefinition.setName("myProperty");
- rootResource.getProperties().add(propertyDefinition);
-
- Either<Resource, StorageOperationStatus> overrideResource = resourceOperation.overrideResource(rootResource, rootResource, false);
-
- assertTrue(overrideResource.isLeft());
- Resource resourceAfter = overrideResource.left().value();
- assertEquals(1, resourceAfter.getProperties().size());
-
- assertNotNull(findProperty(resourceAfter.getProperties(), "myProperty"));
- assertEquals(1, resourceAfter.getCategories().size());
- assertEquals(1, resourceAfter.getCategories().get(0).getSubcategories().size());
-
- assertEquals(updateArr[0], resourceAfter.getCategories().get(0).getName());
- assertEquals(updateArr[1], resourceAfter.getCategories().get(0).getSubcategories().get(0).getName());
-
- resourceOperation.deleteResource(rootResource.getUniqueId());
- }
-
- @Test
- public void testResourceWithCapabilities() {
- String rootName = "Root123";
-
- String userId = "jh0003";
- String category = CATEGORY_NAME;
- String updatedCategory = CATEGORY_NAME_UPDATED;
- deleteAndCreateUser(userId, "first_" + userId, "last_" + userId);
- deleteAndCreateCategory(category);
- deleteAndCreateCategory(updatedCategory);
-
- Resource rootResource = createResource(userId, category, rootName, "1.1", null, false, true);
-
- CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition();
- capabilityTypeDefinition.setType("tosca.capabilities.Container");
- PropertyDefinition delaultProperty1 = new PropertyDefinition();
- delaultProperty1.setName("def");
- delaultProperty1.setType("string");
- delaultProperty1.setDefaultValue("def");
-
- PropertyDefinition delaultProperty2 = new PropertyDefinition();
- delaultProperty2.setName("host");
- delaultProperty2.setType("string");
- delaultProperty2.setDefaultValue("true");
-
- HashMap<String, PropertyDefinition> props = new HashMap<String, PropertyDefinition>();
- props.put(delaultProperty1.getName(), delaultProperty1);
- props.put(delaultProperty2.getName(), delaultProperty2);
- capabilityTypeDefinition.setProperties(props);
-
- Either<CapabilityTypeDefinition, StorageOperationStatus> addTypeRes = capabilityTypeOperation.addCapabilityType(capabilityTypeDefinition);
- assertTrue(addTypeRes.isLeft());
-
- CapabilityDefinition capabilityDefinition = new CapabilityDefinition();
- capabilityDefinition.setDescription("firstCap");
- capabilityDefinition.setName("firstCap");
- capabilityDefinition.setType("tosca.capabilities.Container");
-
- List<ComponentInstanceProperty> properties = new ArrayList<ComponentInstanceProperty>();
- ComponentInstanceProperty propertyDefinition1 = new ComponentInstanceProperty();
- propertyDefinition1.setName("version");
- propertyDefinition1.setType("string");
- propertyDefinition1.setDefaultValue("007");
- properties.add(propertyDefinition1);
-
- ComponentInstanceProperty propertyDefinition2 = new ComponentInstanceProperty();
- propertyDefinition2.setName("host");
- propertyDefinition2.setType("string");
- propertyDefinition2.setDefaultValue("localhost");
- properties.add(propertyDefinition2);
-
- capabilityDefinition.setProperties(properties);
-
- Either<CapabilityDefinition, StorageOperationStatus> addCapabilityRes = capabilityOperation.addCapability(rootResource.getUniqueId(), capabilityDefinition.getName(), capabilityDefinition);
- assertTrue(addCapabilityRes.isLeft());
-
- List<PropertyDefinition> newProperties = new ArrayList<PropertyDefinition>();
- propertyDefinition1 = new ComponentInstanceProperty();
- propertyDefinition1.setName("num_cpu");
- propertyDefinition1.setType("string");
- propertyDefinition1.setDefaultValue("4");
- newProperties.add(propertyDefinition1);
-
- propertyDefinition2 = new ComponentInstanceProperty();
- propertyDefinition2.setName("port");
- propertyDefinition2.setType("string");
- propertyDefinition2.setDefaultValue("4444");
- newProperties.add(propertyDefinition2);
-
- CapabilityDefinition addedCap = addCapabilityRes.left().value();
-
- Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesRes = capabilityOperation.updatePropertiesOfCapability(addedCap.getUniqueId(), addedCap.getType(), newProperties);
- assertTrue(updatePropertiesRes.isLeft());
-
- PropertyDefinition invalidProperty = new PropertyDefinition();
- invalidProperty.setName("port");
- invalidProperty.setType("rrr");
- invalidProperty.setDefaultValue("666");
- newProperties.add(invalidProperty);
-
- Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesInvalidRes = capabilityOperation.updatePropertiesOfCapability(addedCap.getUniqueId(), addedCap.getType(), newProperties);
- assertTrue(updatePropertiesInvalidRes.isRight());
-
- Either<CapabilityDefinition, StorageOperationStatus> getCapabilityRes = capabilityOperation.getCapability(addedCap.getUniqueId());
- assertTrue(getCapabilityRes.isLeft());
-
- Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesOfCapabilityRes = capabilityOperation.deletePropertiesOfCapability(addedCap.getUniqueId());
- assertTrue(deletePropertiesOfCapabilityRes.isLeft());
-
- StorageOperationStatus deleteCapabilityRes = capabilityOperation.deleteCapabilityFromGraph(addedCap.getUniqueId());
- assertTrue(deleteCapabilityRes.equals(StorageOperationStatus.OK));
-
- getCapabilityRes = capabilityOperation.getCapability(addedCap.getUniqueId());
- assertTrue(getCapabilityRes.isRight() && getCapabilityRes.right().value().equals(StorageOperationStatus.NOT_FOUND));
-
- resourceOperation.deleteResource(rootResource.getUniqueId());
- }
-
- private PropertyDefinition findProperty(List<PropertyDefinition> properties, String propName) {
-
- if (properties == null) {
- return null;
- }
-
- for (PropertyDefinition propertyDefinition : properties) {
- String name = propertyDefinition.getName();
- if (name.equals(propName)) {
- return propertyDefinition;
- }
- }
-
- return null;
- }
-
- @Test
- public void testOverrideResourceNotExist() {
- String rootName = "Root123";
-
- String userId = "jh0003";
- String category = CATEGORY_NAME;
- deleteAndCreateUser(userId, "first_" + userId, "last_" + userId);
- deleteAndCreateCategory(category);
-
- Resource rootResource = buildResourceMetadata(userId, category, rootName, "1.1");
- rootResource.setUniqueId(UniqueIdBuilder.buildResourceUniqueId());
-
- Either<Resource, StorageOperationStatus> overrideResource = resourceOperation.overrideResource(rootResource, rootResource, false);
-
- assertTrue(overrideResource.isRight());
-
- }
-
- @Ignore
- @Test
- public void testCatalogResource() {
- String resName = "myResource";
- String userId = "jh0003";
- String category = CATEGORY_NAME;
- deleteAndCreateCategory(category);
- // resourceOperation.deleteResource(UniqueIdBuilder.buildResourceUniqueId(resName,"0.1"));
- Resource newResource = createResource(userId, category, resName, "0.1", null, false, true);
- String resourceId = newResource.getUniqueId();
-
- Map<String, Object> propertiesToMatch = new HashMap<>();
- propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
-
- Either<Set<Resource>, StorageOperationStatus> catalog = resourceOperation.getCatalogData(propertiesToMatch, false);
- assertTrue(catalog.isLeft());
- Set<Resource> catalogSet = catalog.left().value();
- Set<String> idSet = new HashSet<>();
- for (Resource resource : catalogSet) {
- idSet.add(resource.getUniqueId());
- }
- assertTrue(idSet.contains(resourceId));
- resourceOperation.deleteResource(resourceId);
- }
-
- @Ignore
- @Test
- public void testTesterFollowed() {
- String rootName = "Test1";
- String rootName2 = "Test2";
- String rootName3 = "Test3";
- String userId = "jh0003";
- String testerUserId = "tt0004";
- String category = CATEGORY_NAME;
- deleteAndCreateUser(testerUserId, "tester", "last");
- deleteAndCreateCategory(category);
-
- String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User);
- Either<UserData, TitanOperationStatus> findUser = titanDao.getNode(key, userId, UserData.class);
- User adminUser = OperationTestsUtil.convertUserDataToUser(findUser.left().value());
- Either<UserData, TitanOperationStatus> findTesterUser = titanDao.getNode(key, testerUserId, UserData.class);
- User testerUser = OperationTestsUtil.convertUserDataToUser(findTesterUser.left().value());
-
- // Create 3 new resources
- Resource resultResource = createResource(userId, category, rootName, "1.0", null, false, true);
- log.debug("{}", resultResource);
- String resourceId = resultResource.getUniqueId();
- Resource resultResource2 = createResource(userId, category, rootName2, "1.0", null, false, true);
- log.debug("{}", resultResource2);
- String resourceId2 = resultResource2.getUniqueId();
- Resource resultResource3 = createResource(userId, category, rootName3, "1.0", null, false, true);
- log.debug("{}", resultResource3);
- String resourceId3 = resultResource3.getUniqueId();
-
- // update 1 resource to READY_FOR_CERTIFICATION
- Either<Resource, StorageOperationStatus> certReqResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Resource, resultResource, adminUser, adminUser, false);
- Resource RFCResource = certReqResponse.left().value();
- assertEquals(RFCResource.getLifecycleState(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
-
- // update 1 resource to CERTIFICATION_IN_PROGRESS
- Either<Resource, StorageOperationStatus> startCertificationResponse = (Either<Resource, StorageOperationStatus>) lifecycleOperation.startComponentCertification(NodeTypeEnum.Resource, resultResource2, testerUser, adminUser, false);
- Resource IPResource = startCertificationResponse.left().value();
- assertEquals(IPResource.getLifecycleState(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
-
- Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
- lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
-
- Either<List<Resource>, StorageOperationStatus> resources = resourceOperation.getTesterFollowed(testerUserId, lifecycleStates, false);
-
- assertTrue(resources.isLeft());
- List<Resource> result = resources.left().value();
-
- List<String> idSet = new ArrayList();
- for (Resource resource : result) {
- idSet.add(resource.getUniqueId());
- }
- assertTrue(idSet.contains(resourceId));
- assertTrue(idSet.contains(resourceId2));
- assertFalse(idSet.contains(resourceId3));
- resourceOperation.deleteResource(resourceId);
- resourceOperation.deleteResource(resourceId2);
- resourceOperation.deleteResource(resourceId3);
-
- }
-
- @Test
- public void getVersionListNotDeleted() {
- String resName = "myResource";
- String userId = "jh0003";
- String category = CATEGORY_NAME;
- deleteAndCreateCategory(category);
-
- Resource newResource = createResource(userId, category, resName, "0.1", null, false, true);
- String resourceId1 = newResource.getUniqueId();
-
- User admin = new User("j", "h", userId, null, "ADMIN", System.currentTimeMillis());
- Either<Resource, StorageOperationStatus> checkoutResource = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, newResource, admin, admin, false);
- assertTrue(checkoutResource.isLeft());
- Resource newResource2 = checkoutResource.left().value();
- String resourceId2 = newResource2.getUniqueId();
-
- Resource newResource3 = createResource(userId, category, resName, "0.1", null, false, true);
- String resourceId3 = newResource3.getUniqueId();
-
- Either<Map<String, String>, TitanOperationStatus> versionList = resourceOperation.getVersionList(NodeTypeEnum.Resource, "0.2", newResource2.getUUID(), newResource2.getSystemName(), ResourceMetadataData.class);
- assertTrue(versionList.isLeft());
- Map<String, String> versionMap = versionList.left().value();
-
- assertTrue(versionMap.size() == 2);
- assertTrue(versionMap.containsValue(resourceId1));
- assertTrue(versionMap.containsValue(resourceId2));
- assertFalse(versionMap.containsValue(resourceId3));
-
- Either<Resource, StorageOperationStatus> deleteResource = resourceOperation.deleteResource(resourceId1);
- assertTrue(deleteResource.isLeft());
- deleteResource = resourceOperation.deleteResource(resourceId2);
- assertTrue(deleteResource.isLeft());
- deleteResource = resourceOperation.deleteResource(resourceId3);
- assertTrue(deleteResource.isLeft());
-
- }
-
- @Test
- public void getVersionListWithDeleted() {
- String resName = "myResource";
- String userId = "jh0003";
- String category = CATEGORY_NAME;
- deleteAndCreateCategory(category);
-
- Resource newResource = createResource(userId, category, resName, "0.1", null, false, true);
- String resourceId1 = newResource.getUniqueId();
-
- User admin = new User("j", "h", userId, null, "ADMIN", System.currentTimeMillis());
- Either<Resource, StorageOperationStatus> checkoutResource = (Either<Resource, StorageOperationStatus>) lifecycleOperation.checkoutComponent(NodeTypeEnum.Resource, newResource, admin, admin, false);
- assertTrue(checkoutResource.isLeft());
- Resource newResource2 = checkoutResource.left().value();
- String resourceId2 = newResource2.getUniqueId();
-
- Either<Resource, StorageOperationStatus> resource = resourceOperation.getResource(resourceId1, false);
- assertTrue(resource.isLeft());
- Either<Component, StorageOperationStatus> markResourceToDelete = resourceOperation.markComponentToDelete(resource.left().value(), false);
- assertTrue(markResourceToDelete.isLeft());
-
- Either<Map<String, String>, TitanOperationStatus> versionList = resourceOperation.getVersionList(NodeTypeEnum.Resource, "0.2", newResource2.getUUID(), newResource2.getSystemName(), ResourceMetadataData.class);
-
- assertTrue(versionList.isLeft());
- Map<String, String> versionMap = versionList.left().value();
-
- assertTrue(versionMap.size() == 1);
- assertFalse(versionMap.containsValue(resourceId1));
- assertTrue(versionMap.containsValue(resourceId2));
-
- Either<Resource, StorageOperationStatus> deleteResource = resourceOperation.deleteResource(resourceId1);
- assertTrue(deleteResource.isLeft());
- deleteResource = resourceOperation.deleteResource(resourceId2);
- assertTrue(deleteResource.isLeft());
- }
-
- // @Test
- // public void getVersionListAfterCertify(){
- // String resName = "myResource";
- // String category = CATEGORY_NAME;
- // deleteAndCreateCategory(category);
- //
- // Resource newResource = createResource(userId, category, resName, "1.0",
- // null, false, true);
- // String resourceId1 = newResource.getUniqueId();
- //
- // User admin = new User("j", "h", userId, null, "ADMIN",
- // System.currentTimeMillis());
- // Either<Resource, StorageOperationStatus> checkoutResource =
- // lifecycleOperation.checkoutResource(newResource, admin, admin, false);
- // assertTrue(checkoutResource.isLeft());
- // Resource resourceToDelete = checkoutResource.left().value();
- // String deletedId = resourceToDelete.getUniqueId();
- //
- // Either<Resource, StorageOperationStatus> resource =
- // resourceOperation.getResource(deletedId, false);
- // assertTrue(resource.isLeft());
- // Either<Resource, StorageOperationStatus> markResourceToDelete =
- // resourceOperation.markResourceToDelete(resource.left().value(), false);
- // assertTrue(markResourceToDelete.isLeft());
- //
- //
- // Resource newResource2 = createResource(userId, category, resName, "2.0",
- // null, false, true);
- // String resourceId2 = newResource2.getUniqueId();
- //
- //
- // Either<Map<String, String>, TitanOperationStatus> versionList =
- // resourceOperation
- // .getVersionList(NodeTypeEnum.Resource, "2.0",
- // newResource2.getUUID(), newResource2.getSystemName(),
- // ResourceData.class);
- // assertTrue(versionList.isLeft());
- // Map<String, String> versionMap = versionList.left().value();
- //
- // assertTrue(versionMap.size()==2);
- // assertTrue(versionMap.containsValue(resourceId1));
- // assertTrue(versionMap.containsValue(resourceId2));
- //
- // assertFalse(versionMap.containsValue(deletedId));
- //
- // Either<Resource, StorageOperationStatus> deleteResource =
- // resourceOperation.deleteResource(resourceId1);
- // assertTrue(deleteResource.isLeft());
- // deleteResource = resourceOperation.deleteResource(resourceId2);
- // assertTrue(deleteResource.isLeft());
- // deleteResource = resourceOperation.deleteResource(deletedId);
- // assertTrue(deleteResource.isLeft());
- //
- // }
-
-// @Test
- public void testDerviedPropertiesInResource() {
-
- try {
- String userId = "jh0003";
- String category = CATEGORY_NAME;
-
- deleteAndCreateUser(userId, "first_" + userId, "last_" + userId);
- deleteAndCreateCategory(category);
-
- Resource createResource1 = createResource(userId, category, "myResource1", "0.1", null, true, false);
- ResourceMetadataData resourceData = new ResourceMetadataData();
- resourceData.getMetadataDataDefinition().setUniqueId(createResource1.getUniqueId());
- resourceData.getMetadataDataDefinition().setState(LifecycleStateEnum.CERTIFIED.name());
- Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanDao.updateNode(resourceData, ResourceMetadataData.class);
- assertTrue(updateNode.isLeft());
-
- Gson gson = new GsonBuilder().setPrettyPrinting().create();
-
- String json = gson.toJson(createResource1);
- log.debug(json);
-
- Resource createResource2 = createResourceOverrideProperty(userId, category, "myResource2", "0.1", createResource1.getName(), true, false);
-
- json = gson.toJson(createResource2);
- log.debug(json);
-
- List<PropertyDefinition> propList1 = new ArrayList<>();
- TitanOperationStatus findAllResourcePropertiesRecursively1 = propertyOperation.findAllResourcePropertiesRecursively(createResource1.getUniqueId(), propList1);
- assertEquals("check search properties succeed", findAllResourcePropertiesRecursively1, TitanOperationStatus.OK);
-
- List<PropertyDefinition> propList2 = new ArrayList<>();
- TitanOperationStatus findAllResourcePropertiesRecursively2 = propertyOperation.findAllResourcePropertiesRecursively(createResource2.getUniqueId(), propList2);
- assertEquals("check search properties succeed", findAllResourcePropertiesRecursively2, TitanOperationStatus.OK);
- // checks that properties with the same names have been overrided properly
- // the sizes of the property lists should be same (we have 2 properties "disk_size" and "num_cpus" only)
- assertEquals("check number of properties", propList1.size(), propList2.size());
- // checks that not overrided property default value in child's list equals to the same property of the parent
- assertEquals("check values of properties are the same", propList1.stream().filter(prop->prop.getName().equals("num_cpus")).findAny().get().getDefaultValue()
- , propList2.stream().filter(prop->prop.getName().equals("num_cpus")).findAny().get().getDefaultValue());
- // checks that an overrided property default value in child's list doesn't equal to the same property of the parent
- assertTrue(!propList1.stream().filter(prop->prop.getName().equals("disk_size")).findAny().get().getDefaultValue().equals(
- propList2.stream().filter(prop->prop.getName().equals("disk_size")).findAny().get().getDefaultValue()));
-
- resourceOperation.deleteResource(createResource1.getUniqueId());
- resourceOperation.deleteResource(createResource2.getUniqueId());
-
- } finally {
-
- }
-
- /*
- * "properties": { "disk_size": { "constraints": [ { "greaterThan": "0" }, { "lessOrEqual": "10" } ], "uniqueId": "res_myresource1.0.1.disk_size", "type": "integer", "required": false, "defaultValue": "10", "description":
- * "Size of the local disk, in Gigabytes (GB), available to applications running on the Compute node." , "isPassword": false }, "num_cpus": { "constraints": [ { "inRange": [ "1", "4" ] } ], "uniqueId": "res_myresource1.0.1.num_cpus", "type":
- * "integer", "required": false, "defaultValue": "2", "description": "Number of (actual or virtual) CPUs associated with the Compute node." , "isPassword": false } },
- */
- }
-
- @Test
- public void getFilteredComponentsTest() {
-
- TitanGenericDao titanGenericDao = Mockito.mock(TitanGenericDao.class);
- IElementOperation elementOperation = Mockito.mock(ElementOperation.class);
- IElementOperation prevElementOperation = this.resourceOperation.getElementOperation();
- this.resourceOperation.setElementOperation(elementOperation);
- this.resourceOperation.setTitanGenericDao(titanGenericDao);
-
- String subCategoryName = "Database";
- String categoryName = "Generic";
- String resourceTypeName = "VFC";
-
- Map<FilterKeyEnum, String> filters = new HashMap<>();
- filters.put(FilterKeyEnum.CATEGORY, categoryName);
- filters.put(FilterKeyEnum.SUB_CATEGORY, subCategoryName);
- filters.put(FilterKeyEnum.RESOURCE_TYPE, resourceTypeName);
-
- prepareMocks(titanGenericDao, elementOperation, subCategoryName, categoryName, resourceTypeName);
- try{
- //search by category, subCategory and resourceType
- Either<List<Resource>, StorageOperationStatus> getFilteredComponentsRes =
- this.resourceOperation.getFilteredComponents(filters, false);
- assertTrue(getFilteredComponentsRes.isLeft());
-
- //search by category and resourceType
- filters.remove(FilterKeyEnum.SUB_CATEGORY);
- getFilteredComponentsRes =
- this.resourceOperation.getFilteredComponents(filters, false);
- assertTrue(getFilteredComponentsRes.isLeft());
-
- //search by resourceType
- filters.remove(FilterKeyEnum.CATEGORY);
- getFilteredComponentsRes =
- this.resourceOperation.getFilteredComponents(filters, false);
- assertTrue(getFilteredComponentsRes.isLeft());
- }finally{
- this.resourceOperation.setTitanGenericDao(this.titanDao);
- this.resourceOperation.setElementOperation(prevElementOperation);
- }
-
-
- }
-
- @SuppressWarnings("unchecked")
- private void prepareMocks(TitanGenericDao titanGenericDao, IElementOperation elementOperation, String subCategoryName, String categoryName, String resourceTypeName) {
- //prepare resource
- ResourceMetadataData resourceMeta = FactoryUtils.createResourceByType(resourceTypeName);
- ImmutablePair<ResourceMetadataData, GraphEdge> resourcePair = new ImmutablePair<ResourceMetadataData, GraphEdge>(resourceMeta, new GraphEdge());
- List<ImmutablePair<ResourceMetadataData, GraphEdge>> resourcePairList = new ArrayList<>();
- resourcePairList.add(resourcePair);
- Either<List<ImmutablePair<ResourceMetadataData, GraphEdge>>, TitanOperationStatus> parentNodes = Either.left(resourcePairList);
- Map<String, Object> resourceProps = new HashMap<String, Object>();
- resourceProps.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceTypeName);
- resourceProps.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
- List<ResourceMetadataData> resourceList = new ArrayList<>();
- resourceList.add(resourceMeta);
- Either<List<ResourceMetadataData>, TitanOperationStatus> getResources = Either.left(resourceList);
-
- //prepare subcategory
- SubCategoryData subCategoryData = new SubCategoryData(NodeTypeEnum.ResourceSubcategory);
- subCategoryData.getSubCategoryDataDefinition().setName(subCategoryName);
- subCategoryData.getSubCategoryDataDefinition().setUniqueId(UUID.randomUUID().toString());
- GraphEdge graphEdge = new GraphEdge();
- Optional<ImmutablePair<SubCategoryData, GraphEdge>> subCategory = Optional.of(new ImmutablePair<>(subCategoryData, graphEdge));
- List<ImmutablePair<SubCategoryData, GraphEdge>> subcategoriesList = new ArrayList<>();
- subcategoriesList.add(subCategory.get());
- Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> subcategories = Either.left(subcategoriesList);
-
- //prepare category
- CategoryData categoryData = new CategoryData(NodeTypeEnum.ResourceNewCategory);
- categoryData.getCategoryDataDefinition().setUniqueId(UUID.randomUUID().toString());
- categoryData.getCategoryDataDefinition().setName(categoryName);
- Either<CategoryData, StorageOperationStatus> categoryResult = Either.left(categoryData);
- List<CategoryData> categoryDataList = new ArrayList<>();
- categoryDataList.add(categoryResult.left().value());
- Either<ImmutablePair<CategoryData, GraphEdge>, TitanOperationStatus> categoryNode =
- Either.left(new ImmutablePair<CategoryData, GraphEdge>(categoryData, new GraphEdge()));
- Map<String, Object> categoryProps = new HashMap<>();
- categoryProps.put(GraphPropertiesDictionary.NAME.getProperty(), categoryName);
-
- //prepare graph
- Either<TitanGraph, TitanOperationStatus> graphResult = Either.left(Mockito.mock(TitanGraph.class));
- TitanGraph titanGraph = graphResult.left().value();
- TitanVertex vertex = Mockito.mock(TitanVertex.class);
- Iterator<Edge> iterCreator = Mockito.mock(Iterator.class);
- Vertex vertexCreator = Mockito.mock(Vertex.class);
- Edge edge = Mockito.mock(Edge.class);
- List<TitanVertex> verteciesList= new ArrayList<>();
- verteciesList.add(vertex);
- Iterable<TitanVertex> vertecies = new ArrayList<>(verteciesList);
- @SuppressWarnings("rawtypes")
- TitanGraphQuery qBuilder = Mockito.mock(GraphCentricQueryBuilder.class);
-
- when(titanGenericDao.getByCriteria(NodeTypeEnum.ResourceNewCategory, categoryProps, CategoryData.class)).thenReturn(Either.left(categoryDataList));
- when(elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class)).thenReturn(categoryResult);
- when(titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), categoryData.getCategoryDataDefinition().getUniqueId(),
- GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class)).thenReturn(subcategories);
- when(titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), null,
- GraphEdgeLabels.CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class)).thenReturn(subcategories);
- when(titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory), (String) subCategoryData.getSubCategoryDataDefinition().getUniqueId(),
- GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceNewCategory, CategoryData.class)).thenReturn(categoryNode);
- when(titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceSubcategory), subCategoryData.getSubCategoryDataDefinition().getUniqueId(),
- GraphEdgeLabels.CATEGORY, NodeTypeEnum.Resource, ResourceMetadataData.class)).thenReturn(parentNodes);
- when(titanGenericDao.getGraph()).thenReturn(graphResult);
- when(vertex.edges(Direction.IN, GraphEdgeLabels.CREATOR.name())).thenReturn(iterCreator);
- when(vertex.edges(Direction.IN, GraphEdgeLabels.LAST_MODIFIER.name())).thenReturn(iterCreator);
- when(iterCreator.hasNext()).thenReturn(true);
- when(iterCreator.next()).thenReturn(edge);
- when(edge.outVertex()).thenReturn(vertexCreator);
- when(titanGenericDao.getProperties(vertex)).thenReturn(resourceProps);
- when(titanGraph.query()).thenReturn(qBuilder);
- when(qBuilder.has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceMeta.getUniqueId())).thenReturn(qBuilder);
- when(qBuilder.vertices()).thenReturn(vertecies);
- when(titanGenericDao.getByCriteria(NodeTypeEnum.Resource, resourceProps, ResourceMetadataData.class))
- .thenReturn(getResources);
- }
-
-}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java
deleted file mode 100644
index 52686fbfa9..0000000000
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperationTest.java
+++ /dev/null
@@ -1,884 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
-import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.ModelTestBase;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.User;
-import org.openecomp.sdc.be.model.category.CategoryDefinition;
-import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation;
-import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.util.OperationTestsUtil;
-import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
-import org.openecomp.sdc.be.resources.data.ArtifactData;
-import org.openecomp.sdc.be.resources.data.UserData;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.thinkaurelius.titan.core.TitanGraph;
-//import com.tinkerpop.blueprints.Vertex;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-import fj.data.Either;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration("classpath:application-context-test.xml")
-public class ServiceOperationTest extends ModelTestBase {
-
- @javax.annotation.Resource(name = "titan-generic-dao")
- private TitanGenericDao titanDao;
-
- @javax.annotation.Resource(name = "service-operation")
- private ServiceOperation serviceOperation;
-
- @javax.annotation.Resource
- private IGraphLockOperation graphLockOperation;
-
- @javax.annotation.Resource
- private ArtifactOperation artifactOperation;
-
- @javax.annotation.Resource(name = "requirement-operation")
- private RequirementOperation requirementOperation;
-
- @javax.annotation.Resource(name = "resource-operation")
- private ResourceOperation resourceOperation;
-
- @javax.annotation.Resource(name = "property-operation")
- private PropertyOperation propertyOperation;
-
- @javax.annotation.Resource(name = "capability-operation")
- private CapabilityOperation capabilityOperation;
-
- @javax.annotation.Resource(name = "capability-type-operation")
- private CapabilityTypeOperation capabilityTypeOperation;
-
- @javax.annotation.Resource(name = "component-instance-operation")
- private ComponentInstanceOperation resourceInstanceOperation;
-
- @javax.annotation.Resource(name = "lifecycle-operation")
- private LifecycleOperation lifecycleOperation;
-
- private static Logger log = LoggerFactory.getLogger(ServiceOperation.class.getName());
- private static String USER_ID = "muUserId";
- private static String CATEGORY_NAME = "category/mycategory";
-
- @BeforeClass
- public static void setupBeforeClass() {
- // ExternalConfiguration.setAppName("catalog-model");
- // String appConfigDir = "src/test/resources/config/catalog-model";
- // ConfigurationSource configurationSource = new
- // FSConfigurationSource(ExternalConfiguration.getChangeListener(),
- // appConfigDir);
-
- // configurationManager = new ConfigurationManager(new
- // ConfigurationSource() {
- //
- // @Override
- // public <T> T getAndWatchConfiguration(Class<T> className,
- // ConfigurationListener configurationListener) {
- // // TODO Auto-generated method stub
- // return null;
- // }
- //
- // @Override
- // public <T> void addWatchConfiguration(Class<T> className,
- // ConfigurationListener configurationListener) {
- // // TODO Auto-generated method stub
- //
- // }
- // });
-
- // String appConfigDir = "src/test/resources/config";
- // ConfigurationSource configurationSource = new
- // FSConfigurationSource(ExternalConfiguration.getChangeListener(),
- // appConfigDir);
- // configurationManager = new ConfigurationManager(configurationSource);
- //
- // Configuration configuration = new Configuration();
- // configuration.setTitanInMemoryGraph(true);
- //// configuration.setTitanInMemoryGraph(false);
- //// configuration.setTitanCfgFile("C:\\Dev\\d2\\D2-SDnC\\catalog-be\\src\\main\\resources\\config\\titan.properties");
- //
- // configurationManager.setConfiguration(configuration);
-
- ModelTestBase.init();
- }
-
- @Before
- public void createUserAndCategory() {
- deleteAndCreateCategory(CATEGORY_NAME);
- deleteAndCreateUser(USER_ID, "first_" + USER_ID, "last_" + USER_ID, null);
- }
-
- @Test
- public void dummyTest() {
-
- }
-
- @Test
- public void testCreateService() {
- String category = CATEGORY_NAME;
- String serviceName = "servceTest";
- String serviceVersion = "0.1";
- String userId = USER_ID;
- Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true);
- log.debug(" *** create **");
- log.debug("{}", serviceAfterSave);
- String uniqueId = serviceAfterSave.getUniqueId();
-
- Either<Service, StorageOperationStatus> serviceGet = serviceOperation.getService(uniqueId);
- assertTrue(serviceGet.isLeft());
- log.debug(" *** get **");
- log.debug("{}", serviceGet.left().value());
-
- Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(uniqueId);
-
- assertTrue(serviceDelete.isLeft());
- log.debug(" *** delete **");
- log.debug("{}", serviceDelete.left().value());
-
- Either<List<ArtifactData>, TitanOperationStatus> artifacts = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, null, ArtifactData.class);
- assertTrue(artifacts.isRight());
- assertEquals(TitanOperationStatus.NOT_FOUND, artifacts.right().value());
-
- serviceOperation.deleteService(serviceAfterSave.getUniqueId());
- }
-
- @Test
- public void testUtilsService() {
- String category = CATEGORY_NAME;
- String serviceName = "servceTest2";
- String serviceVersion = "0.1";
- String userId = USER_ID;
- Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true);
- log.debug(" *** create **");
- log.debug("{}", serviceAfterSave);
- String uniqueId = serviceAfterSave.getUniqueId();
-
- boolean canWorkOnComponent = ComponentValidationUtils.canWorkOnComponent(serviceAfterSave, userId);
- assertTrue(canWorkOnComponent);
-
- StorageOperationStatus lockComponent = graphLockOperation.lockComponent(uniqueId, NodeTypeEnum.Service);
- assertEquals(StorageOperationStatus.OK, lockComponent);
-
- lockComponent = graphLockOperation.unlockComponent(uniqueId, NodeTypeEnum.Service);
- assertEquals(StorageOperationStatus.OK, lockComponent);
-
- Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(uniqueId);
- }
-
- @Test
- public void testInstanceCounter() {
- String category = CATEGORY_NAME;
- String serviceName = "servceTest2";
- String serviceVersion = "0.1";
- String userId = USER_ID;
- Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true);
- log.debug(" *** create **");
- log.debug("{}", serviceAfterSave);
-
- Either<Integer, StorageOperationStatus> counter = serviceOperation.increaseAndGetComponentInstanceCounter(serviceAfterSave.getUniqueId(), NodeTypeEnum.Service, false);
- assertTrue(counter.isLeft());
- assertEquals(new Integer(1), (Integer) counter.left().value());
-
- counter = serviceOperation.increaseAndGetComponentInstanceCounter(serviceAfterSave.getUniqueId(), NodeTypeEnum.Service, false);
- assertTrue(counter.isLeft());
- assertEquals(new Integer(2), (Integer) counter.left().value());
- Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(serviceAfterSave.getUniqueId());
- }
-
- @Test
- public void testAddArtifactToService() {
- String category = CATEGORY_NAME;
- String serviceName = "servceTest2";
- String serviceVersion = "0.1";
- String userId = USER_ID;
- Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true);
- log.debug("{}", serviceAfterSave);
- String serviceId = serviceAfterSave.getUniqueId();
-
- ArtifactDefinition artifactInfo = addArtifactToService(userId, serviceId, "install_apache");
-
- Either<Service, StorageOperationStatus> service = serviceOperation.getService(serviceId);
- assertTrue(service.isLeft());
-
- Map<String, ArtifactDefinition> artifacts = service.left().value().getArtifacts();
- assertEquals(1, artifacts.size());
-
- for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
- String artifactId = entry.getValue().getUniqueId();
- String description = entry.getValue().getDescription();
- assertEquals("hdkfhskdfgh", description);
-
- artifactInfo.setDescription("jghlsk new desfnjdh");
-
- artifactOperation.updateArifactOnResource(artifactInfo, serviceId, artifactId, NodeTypeEnum.Service, false);
- }
-
- service = serviceOperation.getService(serviceId);
- assertTrue(service.isLeft());
-
- artifacts = service.left().value().getArtifacts();
- for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
- String artifactId = entry.getValue().getUniqueId();
- String description = entry.getValue().getDescription();
- assertEquals("jghlsk new desfnjdh", description);
-
- artifactOperation.removeArifactFromResource(serviceId, artifactId, NodeTypeEnum.Service, true, false);
- }
- service = serviceOperation.getService(serviceId);
- assertTrue(service.isLeft());
-
- artifacts = service.left().value().getArtifacts();
- assertEquals(0, artifacts.size());
-
- Either<Service, StorageOperationStatus> serviceDelete = serviceOperation.deleteService(serviceId);
-
- Either<List<ArtifactData>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(NodeTypeEnum.ArtifactRef, null, ArtifactData.class);
- assertTrue(byCriteria.isRight());
- assertEquals(TitanOperationStatus.NOT_FOUND, byCriteria.right().value());
-
- serviceOperation.deleteService(serviceAfterSave.getUniqueId());
-
- }
-
- private ArtifactDefinition addArtifactToService(String userId, String serviceId, String artifactName) {
- ArtifactDefinition artifactInfo = new ArtifactDefinition();
-
- artifactInfo.setArtifactName(artifactName + ".sh");
- artifactInfo.setArtifactType("SHELL");
- artifactInfo.setDescription("hdkfhskdfgh");
- artifactInfo.setPayloadData("UEsDBAoAAAAIAAeLb0bDQz");
-
- artifactInfo.setUserIdCreator(userId);
- String fullName = "Jim H";
- artifactInfo.setUpdaterFullName(fullName);
- long time = System.currentTimeMillis();
- artifactInfo.setCreatorFullName(fullName);
- artifactInfo.setCreationDate(time);
- artifactInfo.setLastUpdateDate(time);
- artifactInfo.setUserIdLastUpdater(userId);
- artifactInfo.setArtifactLabel(artifactName);
- artifactInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(serviceId, artifactInfo.getArtifactLabel()));
-
- Either<ArtifactDefinition, StorageOperationStatus> artifact = artifactOperation.addArifactToComponent(artifactInfo, serviceId, NodeTypeEnum.Service, true, true);
- assertTrue(artifact.isLeft());
- return artifactInfo;
- }
-
- @Test
- public void testFollowed() {
- String category = CATEGORY_NAME;
- String serviceName = "servceTest2";
- String serviceVersion = "0.1";
- String userId = USER_ID;
- Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true);
- log.debug("{}", serviceAfterSave);
- String serviceId = serviceAfterSave.getUniqueId();
-
- Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
- lifecycleStates.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- Set<LifecycleStateEnum> lastStateStates = new HashSet<LifecycleStateEnum>();
- lastStateStates.add(LifecycleStateEnum.CERTIFIED);
-
- Either<List<Service>, StorageOperationStatus> followed = serviceOperation.getFollowed(userId, lifecycleStates, lastStateStates, false);
- assertTrue(followed.isLeft());
- List<Service> list = followed.left().value();
- assertEquals(1, list.size());
- serviceOperation.deleteService(serviceId);
- }
-
- @Test
- public void testUpdateService() {
- String category = CATEGORY_NAME;
- String serviceName = "12";
- String serviceVersion = "0.1";
- String userId = USER_ID;
- Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true);
- log.debug("{}", serviceAfterSave);
- String serviceId = serviceAfterSave.getUniqueId();
- serviceAfterSave.setDescription("new description");
- Either<Service, StorageOperationStatus> updateService = serviceOperation.updateService(serviceAfterSave, false);
- assertTrue(updateService.isLeft());
-
- titanDao.commit();
-
- Either<Service, StorageOperationStatus> serviceAfterUpdate = serviceOperation.getService(serviceId, false);
- assertTrue(serviceAfterUpdate.isLeft());
-
- serviceOperation.deleteService(serviceId);
- assertEquals("new description", serviceAfterUpdate.left().value().getDescription());
-
- }
-
- public Service createService(String userId, String category, String serviceName, String serviceVersion, boolean isHighestVersion) {
-
- Service service = buildServiceMetadata(userId, category, serviceName, serviceVersion);
-
- service.setHighestVersion(isHighestVersion);
-
- Either<Service, StorageOperationStatus> result = serviceOperation.createService(service, true);
-
- log.info(result.toString());
- assertTrue(result.isLeft());
- Service resultService = result.left().value();
-
- // assertEquals("check resource unique id",
- // UniqueIdBuilder.buildServiceUniqueId(serviceName, serviceVersion),
- // resultService.getUniqueId());
- assertEquals("check resource state", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, resultService.getLifecycleState());
-
- return resultService;
- }
-
- // @Test
- public void testCloneFullService() {
- // try{
- String userId = USER_ID;
- Service origService = createService(userId, CATEGORY_NAME, "my-service", "1.0", true);
-
- // add artifacts
- addArtifactToService(userId, origService.getUniqueId(), "install_apache");
- addArtifactToService(userId, origService.getUniqueId(), "start_apache");
-
- // add resource instances
- ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest();
- riTest.setOperations(titanDao, capabilityTypeOperation, requirementOperation, capabilityOperation, resourceOperation, propertyOperation, resourceInstanceOperation);
- riTest.addResourceInstancesAndRelation(origService.getUniqueId());
-
- Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(), false);
- assertTrue(service2.isLeft());
- origService = service2.left().value();
-
- Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
- String json = prettyGson.toJson(origService);
- log.debug(json);
-
- Service fullService = origService;
-
- Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", false);
- assertTrue(createService.isLeft());
- Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation.getServiceByNameAndVersion("my-service", "2.0", null, false);
- assertTrue(serviceAfterCreate.isLeft());
- fullService = serviceAfterCreate.left().value();
-
- Either<Service, StorageOperationStatus> getOrigService = serviceOperation.getServiceByNameAndVersion("my-service", "1.0", null, false);
- assertTrue(getOrigService.isLeft());
- origService = getOrigService.left().value();
-
- // assertEquals(origService.getComponentMetadataDefinition(),
- // fullService.getComponentMetadataDefinition());
- assertEquals(origService.getArtifacts().size(), fullService.getArtifacts().size());
- assertEquals(origService.getComponentInstances().size(), fullService.getComponentInstances().size());
- assertEquals(origService.getComponentInstancesRelations().size(), fullService.getComponentInstancesRelations().size());
-
- origService.setUniqueId(fullService.getUniqueId());
- origService.setVersion(fullService.getVersion());
-
- assertEquals(origService.getComponentMetadataDefinition(), fullService.getComponentMetadataDefinition());
- assertEquals(origService.getCategories(), fullService.getCategories());
-
- serviceOperation.deleteService(origService.getUniqueId());
- serviceOperation.deleteService(serviceAfterCreate.left().value().getUniqueId());
-
- // } finally {
- // titanDao.rollback();
- // Either<Service, StorageOperationStatus> serviceAfterCreate =
- // serviceOperation.getService(UniqueIdBuilder.buildServiceUniqueId("my-service",
- // "2.0"), true);
- // assertTrue(serviceAfterCreate.isRight());
- //
- // Either<Service, StorageOperationStatus> getOrigService =
- // serviceOperation.getService(UniqueIdBuilder.buildServiceUniqueId("my-service",
- // "1.0"), true);
- // assertTrue(getOrigService.isRight());
- // titanDao.rollback();
- // }
- }
-
- // @Test
- public void testCloneServiceWithoutResourceInstances() {
- String userId = USER_ID;
- Service origService = createService(userId, CATEGORY_NAME, "my-service", "1.0", true);
-
- // add artifacts
- addArtifactToService(userId, origService.getUniqueId(), "install_apache");
- addArtifactToService(userId, origService.getUniqueId(), "start_apache");
-
- Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(), false);
- assertTrue(service2.isLeft());
- origService = service2.left().value();
-
- Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
- String json = prettyGson.toJson(origService);
- log.debug(json);
-
- Service fullService = origService;
-
- Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", false);
- assertTrue(createService.isLeft());
- Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation.getServiceByNameAndVersion("my-service", "2.0", null, false);
- assertTrue(serviceAfterCreate.isLeft());
- fullService = serviceAfterCreate.left().value();
-
- Either<Service, StorageOperationStatus> getOrigService = serviceOperation.getServiceByNameAndVersion("my-service", "1.0", null, false);
- assertTrue(getOrigService.isLeft());
- origService = getOrigService.left().value();
-
- // assertEquals(origService.getComponentMetadataDefinition(),
- // fullService.getComponentMetadataDefinition());
- assertEquals(origService.getArtifacts().size(), fullService.getArtifacts().size());
- assertEquals(origService.getComponentInstances(), fullService.getComponentInstances());
- assertEquals(origService.getComponentInstancesRelations(), fullService.getComponentInstancesRelations());
-
- origService.setUniqueId(fullService.getUniqueId());
- origService.setVersion(fullService.getVersion());
-
- assertEquals(origService.getComponentMetadataDefinition(), fullService.getComponentMetadataDefinition());
- assertEquals(origService.getCategories(), fullService.getCategories());
-
- serviceOperation.deleteService(getOrigService.left().value().getUniqueId());
- serviceOperation.deleteService(serviceAfterCreate.left().value().getUniqueId());
-
- // } finally {
- // titanDao.rollback();
- // }
- }
-
- // @Test
- public void testCloneServiceWithoutArtifacts() {
- String userId = USER_ID;
- Service origService = createService(userId, CATEGORY_NAME, "my-service", "1.0", true);
-
- // add resource instances
- ResourceInstanceOperationTest riTest = new ResourceInstanceOperationTest();
- riTest.setOperations(titanDao, capabilityTypeOperation, requirementOperation, capabilityOperation, resourceOperation, propertyOperation, resourceInstanceOperation);
- riTest.addResourceInstancesAndRelation(origService.getUniqueId());
-
- Either<Service, StorageOperationStatus> service2 = serviceOperation.getService(origService.getUniqueId(), false);
- assertTrue(service2.isLeft());
- origService = service2.left().value();
-
- Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
- String json = prettyGson.toJson(origService);
- log.debug(json);
-
- Service fullService = origService;
-
- Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", false);
- assertTrue(createService.isLeft());
- Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation.getServiceByNameAndVersion("my-service", "2.0", null, false);
- assertTrue(serviceAfterCreate.isLeft());
- fullService = serviceAfterCreate.left().value();
-
- Either<Service, StorageOperationStatus> getOrigService = serviceOperation.getServiceByNameAndVersion("my-service", "1.0", null, false);
- assertTrue(getOrigService.isLeft());
- origService = getOrigService.left().value();
-
- assertEquals(origService.getArtifacts(), fullService.getArtifacts());
- assertEquals(origService.getComponentInstances().size(), fullService.getComponentInstances().size());
- assertEquals(origService.getComponentInstancesRelations().size(), fullService.getComponentInstancesRelations().size());
-
- origService.setUniqueId(fullService.getUniqueId());
- origService.setVersion(fullService.getVersion());
-
- assertEquals(origService.getComponentMetadataDefinition(), fullService.getComponentMetadataDefinition());
- assertEquals(origService.getCategories(), fullService.getCategories());
-
- serviceOperation.deleteService(serviceAfterCreate.left().value().getUniqueId());
- serviceOperation.deleteService(getOrigService.left().value().getUniqueId());
-
- // } finally {
- // titanDao.rollback();
- // }
- }
-
- // @Test
- public void testCloneServiceSimple() {
- String userId = USER_ID;
- String serviceName = "serviceToClone";
-
- Service origService = createService(userId, CATEGORY_NAME, serviceName, "1.0", true);
-
- Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
- String json = prettyGson.toJson(origService);
- log.debug(json);
-
- Service fullService = origService;
-
- Either<Service, StorageOperationStatus> createService = serviceOperation.cloneService(fullService, "2.0", false);
- assertTrue(createService.isLeft());
- Either<Service, StorageOperationStatus> serviceAfterCreate = serviceOperation.getServiceByNameAndVersion(serviceName, "2.0", null, false);
- assertTrue(serviceAfterCreate.isLeft());
- fullService = serviceAfterCreate.left().value();
-
- Either<Service, StorageOperationStatus> getOrigService = serviceOperation.getServiceByNameAndVersion(serviceName, "1.0", null, false);
- assertTrue(getOrigService.isLeft());
- origService = getOrigService.left().value();
-
- // assertEquals(origService.getComponentMetadataDefinition(),
- // fullService.getComponentMetadataDefinition());
- assertEquals(origService.getArtifacts(), fullService.getArtifacts());
- assertEquals(origService.getComponentInstances(), fullService.getComponentInstances());
- assertEquals(origService.getComponentInstancesRelations(), fullService.getComponentInstancesRelations());
- origService.setUniqueId(fullService.getUniqueId());
- origService.setVersion(fullService.getVersion());
-
- assertEquals(origService.getComponentMetadataDefinition(), fullService.getComponentMetadataDefinition());
- assertEquals(origService.getCategories(), fullService.getCategories());
-
- serviceOperation.deleteService(getOrigService.left().value().getUniqueId());
- serviceOperation.deleteService(serviceAfterCreate.left().value().getUniqueId());
-
- // } finally {
- // titanDao.rollback();
- // }
- }
-
- private Service buildServiceMetadata(String userId, String category, String serviceName, String serviceVersion) {
-
- Service service = new Service();
- service.setName(serviceName);
- service.setVersion(serviceVersion);
- service.setDescription("description 1");
-
- service.setCreatorUserId(userId);
- service.setContactId("contactId@sdc.com");
- CategoryDefinition categoryDef = new CategoryDefinition();
- categoryDef.setName(category);
-
- List<CategoryDefinition> categories = new ArrayList<>();
- categories.add(categoryDef);
- service.setCategories(categories);
-
- service.setIcon("images/my.png");
- List<String> tags = new ArrayList<String>();
- tags.add("TAG1");
- tags.add("TAG2");
- service.setTags(tags);
- return service;
- }
-
- private void deleteAndCreateCategory(String category) {
- String[] names = category.split("/");
- OperationTestsUtil.deleteAndCreateServiceCategory(category, titanDao);
- OperationTestsUtil.deleteAndCreateResourceCategory(names[0], names[1], titanDao);
-
- /*
- * CategoryData categoryData = new CategoryData(); categoryData.setName(category);
- *
- * titanDao.deleteNode(categoryData, CategoryData.class); Either<CategoryData, TitanOperationStatus> createNode = titanDao.createNode(categoryData, CategoryData.class); System.out.println("after creating caetgory " + createNode);
- */
-
- }
-
- private UserData deleteAndCreateUser(String userId, String firstName, String lastName, String role) {
- UserData userData = new UserData();
- userData.setUserId(userId);
- userData.setFirstName(firstName);
- userData.setLastName(lastName);
- if (role != null && !role.isEmpty()) {
- userData.setRole(role);
- } else {
- userData.setRole("ADMIN");
- }
-
- titanDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), userId, UserData.class);
- titanDao.createNode(userData, UserData.class);
- titanDao.commit();
-
- return userData;
- }
-
- @Test
- public void testCatalogService() {
- String userId = USER_ID;
- String category = CATEGORY_NAME;
- String serviceName = "MyService";
- String serviceVersion = "0.1";
- Service serviceAfterSave = createService(userId, category, serviceName, serviceVersion, true);
- log.debug("{}", serviceAfterSave);
- String serviceId = serviceAfterSave.getUniqueId();
-
- Map<String, Object> propertiesToMatch = new HashMap<>();
- propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
-
- Either<Set<Service>, StorageOperationStatus> catalog = serviceOperation.getCatalogData(propertiesToMatch, false);
- assertTrue(catalog.isLeft());
- Set<Service> catalogSet = catalog.left().value();
- Set<String> idSet = new HashSet<>();
- for (Service service : catalogSet) {
- idSet.add(service.getUniqueId());
- }
- assertTrue(idSet.contains(serviceId));
- serviceOperation.deleteService(serviceId);
- }
-
- @After
- public void teardown() {
- clearGraph();
- }
-
- private void clearGraph() {
- Either<TitanGraph, TitanOperationStatus> graphResult = titanDao.getGraph();
- TitanGraph graph = graphResult.left().value();
-
- Iterable<TitanVertex> vertices = graph.query().vertices();
- if (vertices != null) {
- Iterator<TitanVertex> iterator = vertices.iterator();
- while (iterator.hasNext()) {
- TitanVertex vertex = iterator.next();
- // graph.removeVertex(vertex);
- vertex.remove();
- }
-
- }
- titanDao.commit();
- }
-
- @Test
- public void testTesterFollowed() {
- String serviceName = "Test1";
- String serviceName2 = "Test2";
- String serviceName3 = "Test3";
- String userId = USER_ID;
- String testerUserId = "tt0004";
- String category = CATEGORY_NAME;
- deleteAndCreateUser(testerUserId, "tester", "last", "TESTER");
- // deleteAndCreateCategory(category);
-
- String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User);
- Either<UserData, TitanOperationStatus> findUser = titanDao.getNode(key, userId, UserData.class);
- User adminUser = OperationTestsUtil.convertUserDataToUser(findUser.left().value());
- Either<UserData, TitanOperationStatus> findTesterUser = titanDao.getNode(key, testerUserId, UserData.class);
- User testerUser = OperationTestsUtil.convertUserDataToUser(findTesterUser.left().value());
-
- // Create 3 new services
- Service resultService = createService(userId, category, serviceName, "0.1", false);
- log.debug("{}", resultService);
- String serviceId = resultService.getUniqueId();
- Service resultService2 = createService(userId, category, serviceName2, "0.1", false);
- log.debug("{}", resultService2);
- String serviceId2 = resultService2.getUniqueId();
- Service resultService3 = createService(userId, category, serviceName3, "0.1", false);
- log.debug("{}", resultService3);
- String serviceId3 = resultService3.getUniqueId();
-
- // update 1 service to READY_FOR_CERTIFICATION
- Either<? extends Component, StorageOperationStatus> certReqResponse = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
- Service RFCService = (Service) certReqResponse.left().value();
- assertEquals(RFCService.getLifecycleState(), LifecycleStateEnum.READY_FOR_CERTIFICATION);
-
- // update 1 service to CERTIFICATION_IN_PROGRESS
- Either<? extends Component, StorageOperationStatus> startCertificationResponse = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService2, testerUser, adminUser, false);
- Service IPService = (Service) startCertificationResponse.left().value();
- assertEquals(IPService.getLifecycleState(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
-
- Set<LifecycleStateEnum> lifecycleStates = new HashSet<LifecycleStateEnum>();
- lifecycleStates.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS);
-
- Either<List<Service>, StorageOperationStatus> services = serviceOperation.getTesterFollowed(testerUserId, lifecycleStates, false);
-
- assertTrue(services.isLeft());
- List<Service> result = services.left().value();
-
- List<String> ids = new ArrayList<>();
- for (Service service : result) {
- ids.add(service.getUniqueId());
- }
- assertTrue(ids.contains(serviceId));
- assertTrue(ids.contains(serviceId2));
- assertFalse(ids.contains(serviceId3));
- serviceOperation.deleteService(serviceId);
- serviceOperation.deleteService(serviceId2);
- serviceOperation.deleteService(serviceId3);
-
- }
-
- @Test
- public void testOpsFollowed() {
- String serviceName = "Test1";
- String serviceName2 = "Test2";
- String serviceName3 = "Test3";
- String serviceName4 = "Test4";
- String userId = USER_ID;
- String category = CATEGORY_NAME;
- String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User);
- Either<UserData, TitanOperationStatus> findUser = titanDao.getNode(key, userId, UserData.class);
- User adminUser = OperationTestsUtil.convertUserDataToUser(findUser.left().value());
-
- // Create 4 new services
- Service resultService = createService(userId, category, serviceName, "0.1", false);
- log.debug("{}", resultService);
- String serviceId = resultService.getUniqueId();
- Service resultService2 = createService(userId, category, serviceName2, "0.1", false);
- log.debug("{}", resultService2);
- String serviceId2 = resultService2.getUniqueId();
- Service resultService3 = createService(userId, category, serviceName3, "0.1", false);
- log.debug("{}", resultService3);
- String serviceId3 = resultService3.getUniqueId();
- Service resultService4 = createService(userId, category, serviceName4, "0.1", false);
- log.debug("{}", resultService3);
- String serviceId4 = resultService4.getUniqueId();
-
- // update 1 service to CERTIFIED dist status DISTRIBUTED
- Either<? extends Component, StorageOperationStatus> reqCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
- Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
- Service actualService = (Service) startCertificationResult.left().value();
-
- Either<? extends Component, StorageOperationStatus> certResponse = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
- Service certifiedService = (Service) certResponse.left().value();
- serviceOperation.updateDestributionStatus(resultService, adminUser, DistributionStatusEnum.DISTRIBUTED);
-
- // update 1 service to CERTIFIED dist status DISTRIBUTION_APPROVED
- Either<? extends Component, StorageOperationStatus> reqCertificationResult2 = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
- Either<? extends Component, StorageOperationStatus> startCertificationResult2 = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
- Service actualService2 = (Service) startCertificationResult2.left().value();
-
- Either<? extends Component, StorageOperationStatus> certResponse2 = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
- Service certifiedService2 = (Service) certResponse2.left().value();
- serviceOperation.updateDestributionStatus(resultService2, adminUser, DistributionStatusEnum.DISTRIBUTION_APPROVED);
-
- // update 1 service to CERTIFIED dist status DISTRIBUTION_REJECTED
- Either<? extends Component, StorageOperationStatus> reqCertificationResult3 = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService3, adminUser, adminUser, false);
- Either<? extends Component, StorageOperationStatus> startCertificationResult3 = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService3, adminUser, adminUser, false);
- Service actualService3 = (Service) startCertificationResult3.left().value();
-
- Either<? extends Component, StorageOperationStatus> certResponse3 = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, actualService3, adminUser, adminUser, false);
- Service certifiedService3 = (Service) certResponse3.left().value();
- serviceOperation.updateDestributionStatus(certifiedService3, adminUser, DistributionStatusEnum.DISTRIBUTION_REJECTED);
-
- Map<String, Object> propertiesToMatch = new HashMap<>();
- propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
-
- Set<DistributionStatusEnum> distStatus = new HashSet<DistributionStatusEnum>();
- distStatus.add(DistributionStatusEnum.DISTRIBUTION_APPROVED);
- distStatus.add(DistributionStatusEnum.DISTRIBUTED);
-
- Either<Set<Service>, StorageOperationStatus> services = serviceOperation.getCertifiedServicesWithDistStatus(propertiesToMatch, distStatus, false);
-
- assertTrue(services.isLeft());
- Set<Service> result = services.left().value();
-
- List<String> ids = new ArrayList<>();
- for (Service service : result) {
- ids.add(service.getUniqueId());
- }
- assertTrue(ids.contains(certifiedService.getUniqueId()));
- assertTrue(ids.contains(certifiedService2.getUniqueId()));
- assertFalse(ids.contains(certifiedService3.getUniqueId()));
- assertFalse(ids.contains(resultService4.getUniqueId()));
- serviceOperation.deleteService(serviceId);
- serviceOperation.deleteService(serviceId2);
- serviceOperation.deleteService(serviceId3);
- serviceOperation.deleteService(serviceId4);
- }
-
- @Test
- public void testGovernorFollowed() {
- String serviceName = "Test1";
- String serviceName2 = "Test2";
- String serviceName3 = "Test3";
- String userId = USER_ID;
- String category = CATEGORY_NAME;
- String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User);
- Either<UserData, TitanOperationStatus> findUser = titanDao.getNode(key, userId, UserData.class);
- User adminUser = OperationTestsUtil.convertUserDataToUser(findUser.left().value());
-
- // Create 3 new services
- Service resultService = createService(userId, category, serviceName, "0.1", false);
- log.debug("{}", resultService);
- String serviceId = resultService.getUniqueId();
- Service resultService2 = createService(userId, category, serviceName2, "0.1", false);
- log.debug("{}", resultService2);
- String serviceId2 = resultService2.getUniqueId();
- Service resultService3 = createService(userId, category, serviceName3, "0.1", false);
- log.debug("{}", resultService3);
- String serviceId3 = resultService3.getUniqueId();
-
- // update 1 service to CERTIFIED + DISTRIBUTED
- Either<? extends Component, StorageOperationStatus> reqCertificationResult = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
- Either<? extends Component, StorageOperationStatus> startCertificationResult = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService, adminUser, adminUser, false);
- Service actualService = (Service) startCertificationResult.left().value();
-
- Either<? extends Component, StorageOperationStatus> certResponse = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, actualService, adminUser, adminUser, false);
- Service certifiedService = (Service) certResponse.left().value();
- serviceOperation.updateDestributionStatus(certifiedService, adminUser, DistributionStatusEnum.DISTRIBUTED);
-
- // update 1 service to CERTIFIED dist status + DISTRIBUTION_REJECTED
- Either<? extends Component, StorageOperationStatus> reqCertificationResult2 = lifecycleOperation.requestCertificationComponent(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
- Either<? extends Component, StorageOperationStatus> startCertificationResult2 = lifecycleOperation.startComponentCertification(NodeTypeEnum.Service, resultService2, adminUser, adminUser, false);
- Service actualService2 = (Service) startCertificationResult2.left().value();
-
- Either<? extends Component, StorageOperationStatus> certResponse2 = lifecycleOperation.certifyComponent(NodeTypeEnum.Service, actualService2, adminUser, adminUser, false);
- Service certifiedService2 = (Service) certResponse2.left().value();
- serviceOperation.updateDestributionStatus(certifiedService2, adminUser, DistributionStatusEnum.DISTRIBUTED);
-
- Map<String, Object> propertiesToMatch = new HashMap<>();
- propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name());
-
- Either<Set<Service>, StorageOperationStatus> services = serviceOperation.getCertifiedServicesWithDistStatus(propertiesToMatch, null, false);
-
- assertTrue(services.isLeft());
- Set<Service> result = services.left().value();
-
- List<String> ids = new ArrayList<>();
- for (Service service : result) {
- ids.add(service.getUniqueId());
- }
- assertTrue(ids.contains(certifiedService.getUniqueId()));
- assertTrue(ids.contains(certifiedService2.getUniqueId()));
- assertFalse(ids.contains(serviceId3));
- serviceOperation.deleteService(serviceId);
- serviceOperation.deleteService(serviceId2);
- serviceOperation.deleteService(serviceId3);
- }
-
-}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorTest.java
deleted file mode 100644
index 069282367f..0000000000
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.sdc.be.model.operations.impl;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
-import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
-import org.openecomp.sdc.be.model.ComponentInstance;
-import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator;
-
-import java.util.Collections;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-
-public class ToscaDefinitionPathCalculatorTest {
-
- private static final String INSTANCE_ID = "123";
- private static final String OWNER_ID = "321";
-
- private ToscaDefinitionPathCalculator toscaDefinitionPathCalculator;
-
-
- @Before
- public void setUp() throws Exception {
- toscaDefinitionPathCalculator = new ToscaDefinitionPathCalculatorImpl();
- }
-
- @Test
- public void calculatePath_ownerAndComponentInstanceEqual() throws Exception {
- ComponentInstance instance = getComponentInstance(INSTANCE_ID);
- GraphEdge edge = createEdgeWithOwner(INSTANCE_ID);
- List<String> definitionPath = toscaDefinitionPathCalculator.calculateToscaDefinitionPath(instance, edge);
- assertEquals(1, definitionPath.size());
- assertEquals(INSTANCE_ID, definitionPath.get(0));
- }
-
- @Test
- public void calculatePath() throws Exception {
- ComponentInstance instance = getComponentInstance(INSTANCE_ID);
- GraphEdge edge = createEdgeWithOwner(OWNER_ID);
- List<String> definitionPath = toscaDefinitionPathCalculator.calculateToscaDefinitionPath(instance, edge);
- assertEquals(2, definitionPath.size());
- assertEquals(INSTANCE_ID, definitionPath.get(0));
- assertEquals(OWNER_ID, definitionPath.get(1));
-
- }
-
-
- private ComponentInstance getComponentInstance(String instanceId) {
- ComponentInstance instance = new ComponentInstance();
- instance.setUniqueId(instanceId);
- return instance;
- }
-
- private GraphEdge createEdgeWithOwner(String owner) {
- GraphEdge edge = new GraphEdge();
- edge.setProperties(Collections.singletonMap(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), owner));
- return edge;
- }
-
-}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java
index ed496b5e92..3a8bb7f8e7 100644
--- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperationTest.java
@@ -20,24 +20,7 @@
package org.openecomp.sdc.be.model.operations.impl;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.time.Instant;
-import java.time.LocalDateTime;
-import java.time.temporal.TemporalField;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
+import fj.data.Either;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
@@ -59,12 +42,17 @@ import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.ModelTestBase;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
-import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation;
import org.openecomp.sdc.be.resources.data.UserData;
import org.openecomp.sdc.common.api.UserRoleEnum;
-import fj.data.Either;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.*;
public class UserAdminOperationTest extends ModelTestBase {
private static final TitanGenericDao titanGenericDao = mock(TitanGenericDao.class);
@@ -97,33 +85,6 @@ public class UserAdminOperationTest extends ModelTestBase {
assertTrue(eitherUser.isLeft());
User user = eitherUser.left().value();
assertTrue(user.getStatus() == UserStatusEnum.INACTIVE);
-
- }
-
- /*
- * @Test public void testDeActivateUserDataFail(){ UserData userData = mockTitanGet(ADMIN, UserRoleEnum.ADMIN, false);
- *
- * Either<User, StorageOperationStatus> eitherUser = userAdminOperation.deActivateUser(userAdminOperation.convertToUser( userData));
- *
- * verify(titanGenericDao, times(0)).updateNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); verify(titanGenericDao, times(0)).deleteNode(Mockito.any(UserData.class), Mockito.eq(UserData.class)); assertTrue(eitherUser.isRight());
- * assertTrue(eitherUser.right().value() == StorageOperationStatus.USER_INACTIVE);
- *
- * }
- */
-
- @Test
- public void testGetAllUsers() throws Exception {
- UserData user1 = mockTitanGet("user1", UserRoleEnum.ADMIN, true);
- UserData user2 = mockTitanGet("user2", UserRoleEnum.DESIGNER, false);
- UserData user3 = mockTitanGet("user3", UserRoleEnum.PRODUCT_MANAGER, true);
- when(titanGenericDao.getAll(NodeTypeEnum.User, UserData.class)).thenReturn(Either.left(Arrays.asList(user1, user2, user3)));
-
- List<User> allUsers = userAdminOperation.getAllUsers().left().value();
- assertEquals(3, allUsers.size());
- assertUserEquals(user1, allUsers.get(0));
- assertUserEquals(user2, allUsers.get(1));
- assertUserEquals(user3, allUsers.get(2));
- verify(titanGenericDao).commit();
}
@Test
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverterTest.java
new file mode 100644
index 0000000000..84f2254bbb
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/DataTypePropertyConverterTest.java
@@ -0,0 +1,187 @@
+package org.openecomp.sdc.be.model.tosca.converters;
+
+import com.google.gson.JsonObject;
+import org.junit.Before;
+import org.junit.Test;
+import org.openecomp.sdc.be.model.DataTypeDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+
+import javax.json.Json;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class DataTypePropertyConverterTest {
+
+ private static final String EMPTY_JSON_STR = "{}";
+ public static final String PROPERTY2_DEFAULT = "{\"prop1\":\"def1\",\"prop3\":\"def3\"}";
+ private DataTypePropertyConverter testInstance = DataTypePropertyConverter.getInstance();
+ private Map<String, DataTypeDefinition> dataTypes;
+ private DataTypeDefinition noDefaultValue, dataType1, dataType2, dataType3;
+ private PropertyDefinition prop1, prop2, prop3, noDefaultProp;
+
+ @Before
+ public void setUp() throws Exception {
+ dataTypes = new HashMap<>();
+
+ prop1 = new PropertyDefinition();
+ prop1.setDefaultValue("def1");
+ prop1.setName("prop1");
+
+ prop2 = new PropertyDefinition();
+ prop2.setType("dataType1");
+ prop2.setName("prop2");
+
+ prop3 = new PropertyDefinition();
+ prop3.setDefaultValue("def3");
+ prop3.setName("prop3");
+
+ noDefaultProp = new PropertyDefinition();
+ noDefaultProp.setName("noDefaultProp");
+
+ noDefaultValue = new DataTypeDefinition();
+ noDefaultValue.setProperties(Collections.singletonList(noDefaultProp));
+
+ dataType1 = new DataTypeDefinition();
+ dataType1.setProperties(Arrays.asList(prop1, prop3));
+
+ dataType2 = new DataTypeDefinition();
+ dataType2.setDerivedFrom(dataType1);
+
+ dataType3 = new DataTypeDefinition();
+ dataType3.setProperties(Collections.singletonList(prop2));
+ dataType3.setDerivedFrom(noDefaultValue);
+
+ dataTypes.put("noDefault", noDefaultValue);
+ dataTypes.put("dataType1", dataType1);
+ dataTypes.put("dataType2", dataType2);
+ dataTypes.put("dataType3", dataType3);
+ }
+
+ @Test
+ public void testGetPropertyDefaultValuesRec_dataTypeNotExist() throws Exception {
+ String defaultValue = testInstance.getDataTypePropertiesDefaultValuesRec("someType", dataTypes);
+ assertEquals(EMPTY_JSON_STR, defaultValue);
+ }
+
+ @Test
+ public void testGetPropertyDefaultValuesRec_NoDefaultValue() throws Exception {
+ String defaultValue = testInstance.getDataTypePropertiesDefaultValuesRec("noDefault", dataTypes);
+ assertEquals(EMPTY_JSON_STR, defaultValue);
+ }
+
+ @Test
+ public void testGetPropertyDefaultValuesRec() throws Exception {
+ String defaultValue = testInstance.getDataTypePropertiesDefaultValuesRec("dataType1", dataTypes);
+ assertEquals(PROPERTY2_DEFAULT, defaultValue);
+ }
+
+ @Test
+ public void testGetPropertyDefaultValuesRec_defaultFromDerivedDataType_derivedDataTypeHasNoDefaults() throws Exception {
+ dataType2.setDerivedFrom(noDefaultValue);
+ String defaultValue = testInstance.getDataTypePropertiesDefaultValuesRec("dataType2", dataTypes);
+ assertEquals(EMPTY_JSON_STR, defaultValue);
+ }
+
+ @Test
+ public void testGetPropertyDefaultValuesRec_defaultFromDerivedDataType() throws Exception {
+ String defaultValue = testInstance.getDataTypePropertiesDefaultValuesRec("dataType2", dataTypes);
+ assertEquals(PROPERTY2_DEFAULT, defaultValue);
+ }
+
+ @Test
+ public void testGetPropertyDefaultValuesRec_defaultFromDataTypesOfProperties_dataTypeOfPropertyHasNoDefault() throws Exception {
+ dataType3.getProperties().get(0).setType(noDefaultValue.getName());
+ String defaultValue = testInstance.getDataTypePropertiesDefaultValuesRec("dataType3", dataTypes);
+ assertEquals(EMPTY_JSON_STR, defaultValue);
+ }
+
+ @Test
+ public void testGetPropertyDefaultValuesRec_defaultFromDataTypesOfProperties() throws Exception {
+ String defaultValue = testInstance.getDataTypePropertiesDefaultValuesRec("dataType3", dataTypes);
+ assertEquals("{\"prop2\":" + PROPERTY2_DEFAULT + "}", defaultValue);//data type 3 has property prop2 which has a data type with property prop1 which has a default value
+ }
+
+ @Test
+ public void testMergeDefaultValues_allDefaultValuesAreOverridden() throws Exception {
+ JsonObject value = new JsonObject();
+ value.addProperty(noDefaultProp.getName(), "override1");
+
+ JsonObject prop1Val = new JsonObject();
+ prop1Val.addProperty(prop1.getName(), "prop1Override");
+
+ JsonObject prop3Val = new JsonObject();
+ prop3Val.addProperty(prop3.getName(), "prop3Override");
+
+ JsonObject prop2Value = new JsonObject();
+ prop2Value.add(prop3.getName(), prop3Val);
+ prop2Value.add(prop1.getName(), prop1Val);
+
+ value.add(prop2.getName(), prop2Value);
+
+ String valBeforeMerge = value.toString();
+
+ testInstance.mergeDataTypeDefaultValuesWithPropertyValue(value, "dataType3", dataTypes);
+ assertEquals(valBeforeMerge, value.toString());
+ }
+
+ @Test
+ public void testMergeDefaultValues() throws Exception {
+ JsonObject value = new JsonObject();
+ value.addProperty(noDefaultProp.getName(), "override1");
+
+ JsonObject prop1Val = new JsonObject();
+ prop1Val.addProperty(prop1.getName(), "prop1Override");
+
+ value.add(prop2.getName(), prop1Val);
+
+ testInstance.mergeDataTypeDefaultValuesWithPropertyValue(value, "dataType3", dataTypes);
+
+ assertEquals("{\"noDefaultProp\":\"override1\",\"prop2\":{\"prop1\":\"prop1Override\",\"prop3\":\"def3\"}}",
+ value.toString());//expect to merge prop 3 default as it was not overridden
+ }
+
+ @Test
+ public void testMergeDefaultValues_mergeAll() throws Exception {
+ JsonObject value = new JsonObject();
+ testInstance.mergeDataTypeDefaultValuesWithPropertyValue(value, "dataType3", dataTypes);
+
+ assertEquals("{\"prop2\":" + PROPERTY2_DEFAULT + "}",
+ value.toString());//expect to merge prop 3 default as it was not overridden
+ }
+
+ @Test
+ public void testMergeDefaultValues_doNotAddDefaultsForGetInputValues() throws Exception {
+
+ JsonObject getInputValue = new JsonObject();
+ getInputValue.addProperty("get_input", "in1");
+
+ JsonObject value = new JsonObject();
+ value.add(prop2.getName(), getInputValue);
+
+ testInstance.mergeDataTypeDefaultValuesWithPropertyValue(value, "dataType3", dataTypes);
+
+ assertEquals("{\"prop2\":{\"get_input\":\"in1\"}}", value.toString());
+ }
+
+ @Test
+ public void testMergeDefaultValues_doNotAddDefaultsForGetInputInnerValues() throws Exception {
+ JsonObject getInputValue = new JsonObject();
+ getInputValue.addProperty("get_input", "in1");
+
+ JsonObject prop1Val = new JsonObject();
+ prop1Val.add(prop1.getName(), getInputValue);
+
+ JsonObject value = new JsonObject();
+ value.add(prop2.getName(), prop1Val);
+
+ testInstance.mergeDataTypeDefaultValuesWithPropertyValue(value, "dataType3", dataTypes);
+
+ assertEquals("{\"prop2\":{\"prop1\":{\"get_input\":\"in1\"},\"prop3\":\"def3\"}}", value.toString());
+
+ }
+}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverterTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverterTest.java
new file mode 100644
index 0000000000..285dd9a965
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverterTest.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.be.model.tosca.converters;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class HeatStringConverterTest {
+
+ @Test
+ public void convertString_strWithQuotes_returnStringAsIs() {
+ String str = "'i'm string with \"quote\"'";
+ String convert = HeatStringConverter.getInstance().convert(str, null, null);
+ assertEquals(str, convert);
+ }
+
+}
diff --git a/catalog-ui/package.json b/catalog-ui/package.json
index 6e86b46dd0..3e13e69a2b 100644
--- a/catalog-ui/package.json
+++ b/catalog-ui/package.json
@@ -45,6 +45,7 @@
"raw-loader": "^0.5.1",
"sass-loader": "^4.1.1",
"script-loader": "^0.7.0",
+ "sdc-ui": "^1.6.2",
"source-map-loader": "^0.1.5",
"style-loader": "^0.13.1",
"url-loader": "^0.5.7",
@@ -105,7 +106,6 @@
"js-md5": "^0.4.2",
"lodash": "^4.17.2",
"ng-infinite-scroll": "^1.3.0",
- "ng2-interceptors": "^1.3.0-1",
"perfect-scrollbar": "^0.6.16",
"qtip2": "^3.0.3",
"reflect-metadata": "^0.1.10",
diff --git a/catalog-ui/src/app/models.ts b/catalog-ui/src/app/models.ts
index f3eb5d5fa6..ec70ebe8b1 100644
--- a/catalog-ui/src/app/models.ts
+++ b/catalog-ui/src/app/models.ts
@@ -95,6 +95,7 @@ export * from './models/member';
export * from './models/modules/base-module';
export * from './models/properties';
export * from './models/requirement';
+export * from './models/server-error-response';
export * from './models/tab';
export * from './models/tooltip-data';
export * from './models/user';
diff --git a/catalog-ui/src/app/models/modal.ts b/catalog-ui/src/app/models/modal.ts
index 51aa5e19a7..b7bdf251fe 100644
--- a/catalog-ui/src/app/models/modal.ts
+++ b/catalog-ui/src/app/models/modal.ts
@@ -5,12 +5,14 @@ export class ModalModel {
title: string;
content: any;
buttons: Array<ButtonModel>;
+ type: string; 'standard|error|alert'
- constructor(size?: string, title?: string, content?: any, buttons?: Array<ButtonModel>) {
+ constructor(size?: string, title?: string, content?: any, buttons?: Array<ButtonModel>, type?:string) {
this.size = size;
this.title = title;
this.content = content;
this.buttons = buttons;
+ this.type = type || 'standard';
}
}
diff --git a/catalog-ui/src/app/models/server-error-response.ts b/catalog-ui/src/app/models/server-error-response.ts
new file mode 100644
index 0000000000..61d09af48b
--- /dev/null
+++ b/catalog-ui/src/app/models/server-error-response.ts
@@ -0,0 +1,84 @@
+/*-
+ * ============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=========================================================
+ */
+
+/**
+ * Created by ngordon on 7/27/2017.
+ */
+
+import { Response } from '@angular/http';
+import { SEVERITY, ServerErrors } from "../utils/constants";
+
+export class ServerErrorResponse {
+
+ title: string;
+ message: string;
+ messageId: string;
+ status: number;
+ severity: SEVERITY;
+
+ constructor(response?: Response) {
+
+ if (response) {
+ let rejectionObj: any = {};
+ if (response.text().length) {
+ let rejection = response.json();
+ rejectionObj = rejection.serviceException || rejection.requestError && (rejection.requestError.serviceException || rejection.requestError.policyException);
+ rejectionObj.text = this.getFormattedMessage(rejectionObj.text || ServerErrors.MESSAGE_ERROR, rejectionObj.variables);
+ }
+
+ this.title = ServerErrors.ERROR_TITLE;
+ this.message = rejectionObj.text || response.statusText || ServerErrors.DEFAULT_ERROR;
+ this.messageId = rejectionObj.messageId;
+ this.status = response.status;
+ this.severity = SEVERITY.ERROR;
+ }
+ }
+
+
+ private getFormattedMessage = (text: string, variables: Array<string>): string => { //OLD CODE
+ // Remove the "Error: " text at the begining
+ if (text.trim().indexOf("Error:") === 0) {
+ text = text.replace("Error:", "").trim();
+ }
+
+ //mshitrit DE199895 bug fix
+ let count: number = 0;
+ variables.forEach(function (item) {
+ variables[count] = item ? item.replace('<', '&lt').replace('>', '&gt') : '';
+ count++;
+ });
+
+ // Format the message in case has array to <ul><li>
+ text = text.replace(/\[%(\d+)\]/g, function (_, m) {
+ let tmp = [];
+ let list = variables[--m].split(";");
+ list.forEach(function (item) {
+ tmp.push("<li>" + item + "</li>");
+ });
+ return "<ul>" + tmp.join("") + "</ul>";
+ });
+
+ // Format the message %1 %2
+ text = text.format(variables);
+
+ return text;
+
+ };
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/ng2/app.module.ts b/catalog-ui/src/app/ng2/app.module.ts
index 57adb8fd66..88c2d876c4 100644
--- a/catalog-ui/src/app/ng2/app.module.ts
+++ b/catalog-ui/src/app/ng2/app.module.ts
@@ -32,14 +32,13 @@ import {
} from "./utils/ng1-upgraded-provider";
import {ConfigService} from "./services/config.service";
import {HttpModule} from '@angular/http';
+import {HttpService} from './services/http.service';
import {AuthenticationService} from './services/authentication.service';
import {Cookie2Service} from "./services/cookie.service";
import {ComponentServiceNg2} from "./services/component-services/component.service";
import {ServiceServiceNg2} from "./services/component-services/service.service";
import {ComponentInstanceServiceNg2} from "./services/component-instance-services/component-instance.service";
-import { InterceptorService } from 'ng2-interceptors';
import { XHRBackend, RequestOptions } from '@angular/http';
-import {HttpInterceptor} from "./services/http.interceptor.service";
import { SearchBarComponent } from './shared/search-bar/search-bar.component';
import { SearchWithAutoCompleteComponent } from './shared/search-with-autocomplete/search-with-autocomplete.component';
@@ -49,16 +48,6 @@ export function configServiceFactory(config:ConfigService) {
return () => config.loadValidationConfiguration();
}
-export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions){
- let service = new InterceptorService(xhrBackend, requestOptions);
- service.addInterceptor(new HttpInterceptor());
- return service;
-}
-
-
-// export function httpServiceFactory(backend: XHRBackend, options: RequestOptions) {
-// return new HttpService(backend, options);
-// }
@NgModule({
declarations: [
@@ -87,6 +76,7 @@ export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: Reque
ConfigService,
ComponentServiceNg2,
ServiceServiceNg2,
+ HttpService,
ComponentInstanceServiceNg2,
{
provide: APP_INITIALIZER,
@@ -94,11 +84,6 @@ export function interceptorFactory(xhrBackend: XHRBackend, requestOptions: Reque
deps: [ConfigService],
multi: true
},
- {
- provide: InterceptorService,
- useFactory: interceptorFactory,
- deps: [XHRBackend, RequestOptions]
- }
],
bootstrap: [AppComponent]
})
diff --git a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.ts b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.ts
index 8b27ab7e3a..3339b605ca 100644
--- a/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.ts
+++ b/catalog-ui/src/app/ng2/components/dynamic-element/elements-ui/integer-input/ui-element-integer-input.component.ts
@@ -35,7 +35,7 @@ export class UiElementIntegerInputComponent extends UiElementBase implements UiE
onSave() {
if (!this.control.invalid){
- this.baseEmitter.emit(JSON.parse(this.value));
+ this.baseEmitter.emit(this.value ? JSON.parse(this.value) : this.value);
}
}
}
diff --git a/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.html b/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.html
index 38de3ce649..2b58d0f086 100644
--- a/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.html
+++ b/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.html
@@ -1,5 +1,5 @@
<div class="properties-table">
- <loader [display]="isLoading" size="large" [relative]="false"></loader>
+ <loader [display]="isLoading" [size]="'large'" [relative]="true"></loader>
<div class="table-header">
<div class="table-cell col1">Property Name</div>
<div class="table-cell col3">From Instance</div>
diff --git a/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.ts b/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.ts
index 30cdb89d8e..736655f3f7 100644
--- a/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.ts
+++ b/catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.ts
@@ -57,7 +57,7 @@ export class InputsTableComponent {
openDeleteModal = (input:InputFEModel) => {
this.selectedInputToDelete = input;
- this.modalService.openActionModal("Delete Input", "Are you sure you want to delete this input?", "Delete", this.onDeleteInput, "Close");
+ this.modalService.createActionModal("Delete Input", "Are you sure you want to delete this input?", "Delete", this.onDeleteInput, "Close").instance.open();
}
}
diff --git a/catalog-ui/src/app/ng2/components/loader/loader.component.html b/catalog-ui/src/app/ng2/components/loader/loader.component.html
index 0e13cee674..a62aa114d9 100644
--- a/catalog-ui/src/app/ng2/components/loader/loader.component.html
+++ b/catalog-ui/src/app/ng2/components/loader/loader.component.html
@@ -1,4 +1,5 @@
-<div *ngIf="display" data-tests-id="tlv-loader">
+<div *ngIf="isVisible" data-tests-id="tlv-loader" [ngClass]="relative ? 'loader-relative' : 'loader-fixed'"
+ [style.top]="offset.top" [style.left]="offset.left" [style.width]="offset.width" [style.height]="offset.height">
<div class="tlv-loader-back" [ngClass]="{'tlv-loader-relative':relative}"></div>
<div class="tlv-loader {{size}}"></div>
</div>
diff --git a/catalog-ui/src/app/ng2/components/loader/loader.component.less b/catalog-ui/src/app/ng2/components/loader/loader.component.less
index 054b6021a1..ddb9915176 100644
--- a/catalog-ui/src/app/ng2/components/loader/loader.component.less
+++ b/catalog-ui/src/app/ng2/components/loader/loader.component.less
@@ -16,6 +16,22 @@
z-index: 10002;
}
+.loader-relative {
+ display: block;
+ position:absolute;
+ width: 100%;
+ height:100%;
+}
+
+.loader-fixed {
+ display: block;
+ position:fixed;
+ top:0;
+ left:0;
+ width: 100%;
+ height:100%;
+}
+
@keyframes fadein {
from { opacity: 0; }
to { opacity: 0.8; }
diff --git a/catalog-ui/src/app/ng2/components/loader/loader.component.ts b/catalog-ui/src/app/ng2/components/loader/loader.component.ts
index 92278d3ff5..f66aa551e2 100644
--- a/catalog-ui/src/app/ng2/components/loader/loader.component.ts
+++ b/catalog-ui/src/app/ng2/components/loader/loader.component.ts
@@ -21,7 +21,7 @@
/**
* Created by rc2122 on 6/6/2017.
*/
-import {Component, Input, ElementRef, Renderer, SimpleChanges} from "@angular/core";
+import { Component, Input, ViewContainerRef, SimpleChanges} from "@angular/core";
@Component({
selector: 'loader',
templateUrl: './loader.component.html',
@@ -29,13 +29,20 @@ import {Component, Input, ElementRef, Renderer, SimpleChanges} from "@angular/co
})
export class LoaderComponent {
- @Input() display:boolean;
- @Input() size:string;// small || medium || large
- @Input() relative: boolean;
- @Input() elementSelector: string; // optional. If is relative is set to true, option to pass in element that loader should be relative to. Otherwise, will be relative to parent element.
+ @Input() display: boolean;
+ @Input() size: string;// small || medium || large
+ @Input() relative: boolean; // If is relative is set to true, loader will appear over parent element. Otherwise, will be fixed over the entire page.
+ @Input() loaderDelay: number; //optional - number of ms to delay loader display.
+ private isVisible: boolean = false;
+ private offset : {
+ top: string;
+ left: string;
+ width: string;
+ height: string;
+ };
- constructor (private el: ElementRef, private renderer: Renderer){
+ constructor(private viewContainerRef: ViewContainerRef) {
}
ngOnInit() {
@@ -49,46 +56,31 @@ export class LoaderComponent {
ngOnChanges(changes: SimpleChanges) {
if(changes.display){
- if (this.display) {
- this.changeLoaderDisplay(false); //display is set to true, so loader will appear unless we explicitly tell it not to.
- window.setTimeout((): void => {
- this.display && this.changeLoaderDisplay(true); //only show loader if we still need to display it.
- }, 500);
- } else {
- window.setTimeout(():void => {
- this.changeLoaderDisplay(false);
- }, 0);
- }
+ this.changeLoaderDisplay(this.display);
}
}
- changeLoaderDisplay = (display: boolean): void => {
+ private changeLoaderDisplay = (display: boolean): void => {
if (display) {
- this.calculateLoaderPosition();
- this.renderer.setElementStyle(this.el.nativeElement, 'display', 'block');
+ window.setTimeout((): void => {
+ this.display && this.showLoader(); //only show loader if this.display has not changed in the meanwhile.
+ }, this.loaderDelay || 0);
} else {
- this.renderer.setElementStyle(this.el.nativeElement, 'display', 'none');
+ this.isVisible = false;
}
}
- calculateLoaderPosition = () => {
- if (this.relative === true) { // Can change the parent position to relative without causing style issues.
- let parent = (this.elementSelector) ? angular.element(this.elementSelector).get(0) : this.el.nativeElement.parentElement;
- this.renderer.setElementStyle(parent, 'position', 'relative');
- this.setLoaderPosition(0, 0); //will be relative to parent and appear over specified element
- //TODO: DONT force parent to have position relative; set inner div's style instead of outer element
- // let parentPos: ClientRect = this.el.nativeElement.parentElement.getBoundingClientRect();
- // this.setLoaderPosition(parentPos.top, parentPos.left, parentPos.width, parentPos.height);
- } else {
- this.setLoaderPosition(0, 0); //will appear over whole page
+ private showLoader = () => {
+ if (this.relative === true) {
+ let parentElement = this.viewContainerRef.element.nativeElement.parentElement;
+ this.offset = {
+ left: (parentElement.offsetLeft) ? parentElement.offsetLeft + "px" : undefined,
+ top: (parentElement.offsetTop) ? parentElement.offsetTop + "px" : undefined,
+ width: (parentElement.offsetWidth) ? parentElement.offsetWidth + "px" : undefined,
+ height: (parentElement.offsetHeight) ? parentElement.offsetHeight + "px" : undefined
+ };
}
+ this.isVisible = true;
}
- setLoaderPosition = (top:number, left:number, width?:number, height?:number): void => {
- this.renderer.setElementStyle(this.el.nativeElement, 'position', 'absolute');
- this.renderer.setElementStyle(this.el.nativeElement, 'top', top? top.toString() : "0");
- this.renderer.setElementStyle(this.el.nativeElement, 'left', left? left.toString() : "0");
- this.renderer.setElementStyle(this.el.nativeElement, 'width', width? width.toString() : "100%");
- this.renderer.setElementStyle(this.el.nativeElement, 'height', height? height.toString() : "100%");
- };
}
diff --git a/catalog-ui/src/app/ng2/components/modal/error-message/error-message.component.html b/catalog-ui/src/app/ng2/components/modal/error-message/error-message.component.html
new file mode 100644
index 0000000000..433bd4fd6f
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/modal/error-message/error-message.component.html
@@ -0,0 +1,5 @@
+<div class="error-message-component">
+ <div>Error code: {{input.messageId}}</div>
+ <div>Status code: {{input.status}}</div>
+ <div class="error-message">{{input.message}}</div>
+</div> \ No newline at end of file
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationException.java b/catalog-ui/src/app/ng2/components/modal/error-message/error-message.component.ts
index 8e958b9ad1..c0d6673412 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/MigrationException.java
+++ b/catalog-ui/src/app/ng2/components/modal/error-message/error-message.component.ts
@@ -18,12 +18,21 @@
* ============LICENSE_END=========================================================
*/
-package org.openecomp.sdc.asdctool.impl.migration;
+/**
+ * Created by ngordon on 7/30/2017.
+ */
+import { Component, Input } from '@angular/core';
+import { ServerErrorResponse } from 'app/models';
+
+@Component({
+ selector: 'error-message',
+ templateUrl: './error-message.component.html'
+})
-public class MigrationException extends RuntimeException {
+export class ErrorMessageComponent {
+ @Input() input: ServerErrorResponse;
- public MigrationException(String message) {
- super(message);
+ constructor() {
}
}
diff --git a/catalog-ui/src/app/ng2/components/modal/modal.component.html b/catalog-ui/src/app/ng2/components/modal/modal.component.html
index cc411bc751..d843867cdb 100644
--- a/catalog-ui/src/app/ng2/components/modal/modal.component.html
+++ b/catalog-ui/src/app/ng2/components/modal/modal.component.html
@@ -1,10 +1,14 @@
<div class="custom-modal {{input.size}}">
<div class="ng2-modal-content">
- <div class="ng2-modal-header">
+ <div class="ng2-modal-header modal-type-{{input.type}}">
<span class="title">{{ input.title }}</span>
<span class="close-button" (click)="close()"></span>
</div>
- <div class="ng2-modal-body" >{{input.content}}</div>
+ <div class="ng2-modal-body" >
+ <div *ngIf="input.content">{{input.content}}</div>
+ <div #dynamicContentContainer></div>
+ </div>
+
<div class="ng2-modal-footer">
<button *ngFor="let button of input.buttons"
class="tlv-btn {{button.cssClass}}"
diff --git a/catalog-ui/src/app/ng2/components/modal/modal.component.less b/catalog-ui/src/app/ng2/components/modal/modal.component.less
index a35f829e6a..c87162afb0 100644
--- a/catalog-ui/src/app/ng2/components/modal/modal.component.less
+++ b/catalog-ui/src/app/ng2/components/modal/modal.component.less
@@ -37,12 +37,25 @@
display: -ms-flexbox;
display: flex;
text-align: left;
- border-bottom: solid 1px @main_color_o;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
margin: 0px 20px;
+
+ &.modal-type-standard {
+ border-bottom: solid 3px @main_color_a;
+ }
+
+ &.modal-type-error {
+ border-bottom: solid 3px @func_color_q;
+ }
+
+ &.modal-type-alert{
+ border-bottom: solid 3px @main_color_h;
+ }
+
.title{
+ .s_18_m;
-webkit-box-flex: 999;
-ms-flex-positive: 999;
flex-grow: 999;
diff --git a/catalog-ui/src/app/ng2/components/modal/modal.component.ts b/catalog-ui/src/app/ng2/components/modal/modal.component.ts
index 09fb9abdd1..89db8d1140 100644
--- a/catalog-ui/src/app/ng2/components/modal/modal.component.ts
+++ b/catalog-ui/src/app/ng2/components/modal/modal.component.ts
@@ -22,7 +22,7 @@
* Created by rc2122 on 6/1/2017.
*/
import { Component, ElementRef, Input, OnInit, OnDestroy } from '@angular/core';
-//import {ViewContainerRef, ViewChild} from '@angular/core';
+import {ViewContainerRef, ViewChild} from '@angular/core';
import * as $ from 'jquery';
import { ButtonsModelMap, ModalModel } from 'app/models';
@@ -34,9 +34,9 @@ import { ButtonsModelMap, ModalModel } from 'app/models';
export class ModalComponent implements OnInit, OnDestroy {
@Input() input: ModalModel;
+ @Input() dynamicContent: any;
+ @ViewChild('dynamicContentContainer', { read: ViewContainerRef }) dynamicContentContainer: ViewContainerRef; //Allows for custom component as body instead of simple message. See ModalService.createActionModal for implementation details, and HttpService's catchError() for example.
private modalElement: JQuery;
- //@ViewChild('modalBody', { read: ViewContainerRef }) modalContainer: ViewContainerRef; //TODO: allow for custom component as body instead of simple message
-
constructor( el: ElementRef ) {
this.modalElement = $(el.nativeElement);
diff --git a/catalog-ui/src/app/ng2/components/modal/modal.module.ts b/catalog-ui/src/app/ng2/components/modal/modal.module.ts
index d77be2cd23..892f6993dd 100644
--- a/catalog-ui/src/app/ng2/components/modal/modal.module.ts
+++ b/catalog-ui/src/app/ng2/components/modal/modal.module.ts
@@ -1,16 +1,19 @@
import { NgModule } from "@angular/core";
import { CommonModule } from '@angular/common';
import { ModalService } from 'app/ng2/services/modal.service';
-import { ModalComponent } from "app/ng2/components/modal/modal.component"
+import { ModalComponent } from "app/ng2/components/modal/modal.component";
+import { ErrorMessageComponent } from "./error-message/error-message.component";
@NgModule({
declarations: [
ModalComponent,
+ ErrorMessageComponent
],
imports: [CommonModule],
exports: [],
- entryComponents: [
- ModalComponent
+ entryComponents: [ //need to add anything that will be dynamically created
+ ModalComponent,
+ ErrorMessageComponent
],
providers: [ModalService]
})
diff --git a/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.html b/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.html
index 95cc79dce9..57da7d90e4 100644
--- a/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.html
+++ b/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.html
@@ -10,7 +10,7 @@
</div>
<div class="table-cell" *ngIf="!canBeDeclared && !property.isChildOfListOrMap">{{property.name}}</div> <!-- simple children of complex type within map or list -->
<div class="table-cell map-entry" *ngIf="property.isChildOfListOrMap && propType == derivedPropertyTypes.MAP"><!-- map left cell -->
- <input [value]="property.mapKey" #mapKey (change)="mapKeyChanged.emit(mapKey)" [readonly]="readonly" type="text" [ngClass]="{'disabled':readonly, 'error':!mapKey.validity.valid}" />
+ <input [value]="property.mapKey" #mapKey (change)="mapKeyChanged.emit(mapKey)" [readonly]="readonly" type="text" [ngClass]="{'disabled':readonly, 'error':!mapKey.validity.valid}" required/>
</div>
</ng-container>
<!-- RIGHT CELL OR FULL WIDTH CELL-->
@@ -23,7 +23,7 @@
[name]="property.name"
[path]="property.propertiesName"
(valueChange)="valueChanged.emit();"
- [readonly]="readonly||property.isDeclared||property.isDisabled"
+ [readonly]="readonly || property.isDeclared || property.isDisabled"
></dynamic-element>
</div>
</ng-container>
diff --git a/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.ts b/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.ts
index 59811b582d..3982e4e8dc 100644
--- a/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.ts
+++ b/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.ts
@@ -112,7 +112,9 @@ export class DynamicPropertyComponent {
//grab the cumulative value for the new item from parent PropertyFEModel and assign that value to DerivedFEProp[0] (which is the list or map parent with UUID of the set we just added)
let parentNames = (<PropertyFEModel>this.property).getParentNamesArray(newProps[0].propertiesName, []);
newProps[0].valueObj = _.get(this.property.valueObj, parentNames.join('.'));
- this.valueChanged.emit(this.property.name);
+ if ( newProps[0].mapKey ) {//prevent saving if it is map item, whem it is list item- the map key is the es type (it will be saved only after user enter key)
+ this.valueChanged.emit(this.property.name);
+ }
}
}
}
@@ -122,7 +124,9 @@ export class DynamicPropertyComponent {
if (this.property instanceof PropertyFEModel) { // will always be the case
this.property.childPropUpdated(property);
this.dataTypeService.checkForCustomBehavior(this.property);
- this.valueChanged.emit(this.property.name);
+ if (this.property.getParentNamesArray(property.propertiesName, []).indexOf('') === -1) {//If one of the parents is empty key -don't save
+ this.valueChanged.emit(this.property.name);
+ }
}
}
@@ -142,6 +146,9 @@ export class DynamicPropertyComponent {
let oldKey = item.mapKey;
if (target && typeof target.value == 'string') { //allow saving empty string
let replaceKey:string = target.value;
+ if (!replaceKey) {//prevent delete map key
+ return;
+ }
if(Object.keys(itemParent.valueObj).indexOf(replaceKey) > -1){//the key is exists
target.setCustomValidity('This key is already exists.');
return;
@@ -156,11 +163,12 @@ export class DynamicPropertyComponent {
let itemIndex: number = this.property.flattenedChildren.filter(prop => prop.parentName == item.parentName).map(prop => prop.propertiesName).indexOf(item.propertiesName);
itemParent.valueObj.splice(itemIndex, 1);
}
-
- if (itemParent instanceof PropertyFEModel) { //direct child
- this.valueChanged.emit(this.property.name);
- } else { //nested child - need to update parent prop by getting flattened name (recurse through parents and replace map/list keys, etc)
- this.childValueChanged(itemParent);
+ if (item.mapKey) {//prevent going to BE if user tries to delete map item without key (it was not saved in BE)
+ if (itemParent instanceof PropertyFEModel) { //direct child
+ this.valueChanged.emit(this.property.name);
+ } else { //nested child - need to update parent prop by getting flattened name (recurse through parents and replace map/list keys, etc)
+ this.childValueChanged(itemParent);
+ }
}
}
}
diff --git a/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.html b/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.html
index c57998af5e..a9dc499e7d 100644
--- a/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.html
+++ b/catalog-ui/src/app/ng2/components/properties-table/properties-table.component.html
@@ -1,5 +1,5 @@
<div class="properties-table">
- <loader [display]="isLoading" size="large" [relative]="false"></loader>
+ <loader [display]="isLoading" [size]="'large'" [relative]="true" [loaderDelay]="500"></loader>
<div class="table-header">
<div class="table-cell col1">Property Name</div>
<div class="table-cell col2">Type</div>
diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.module.ts b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.module.ts
index 3a5daba711..1c6f51314d 100644
--- a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.module.ts
+++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.module.ts
@@ -45,7 +45,6 @@ import { KeysPipe } from 'app/ng2/pipes/keys.pipe';
import {TooltipModule} from "../../components/tooltip/tooltip.module";
import { ComponentModeService } from "app/ng2/services/component-mode.service"
import {LoaderComponent} from "app/ng2/components/loader/loader.component"
-import {HttpInterceptor} from "../../services/http.interceptor.service";
@NgModule({
declarations: [
@@ -81,7 +80,7 @@ import {HttpInterceptor} from "../../services/http.interceptor.service";
// PopoverContentComponent,
// PopoverComponent
],
- providers: [PropertiesService, HierarchyNavService, PropertiesUtils, DataTypeService,HttpInterceptor, ContentAfterLastDotPipe, GroupByPipe, KeysPipe, ComponentModeService]
+ providers: [PropertiesService, HierarchyNavService, PropertiesUtils, DataTypeService, ContentAfterLastDotPipe, GroupByPipe, KeysPipe, ComponentModeService]
})
export class PropertiesAssignmentModule {
diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html
index 0b50357a5c..be7e03dccd 100644
--- a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html
+++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.html
@@ -43,7 +43,7 @@
<tabs #hierarchyNavTabs tabStyle="simple-tabs">
<tab tabTitle="Composition">
<div class="hierarchy-nav-container">
- <loader [display]="loadingInstances" size="medium" [relative]="true"></loader>
+ <loader [display]="loadingInstances" [size]="'medium'" [relative]="true" [loaderDelay]="500"></loader>
<div class="hierarchy-header white-sub-header">
<span tooltip="{{component.name}}">{{component.name}}</span>
</div>
diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less
index 8151d001e8..03974bf723 100644
--- a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less
+++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less
@@ -1,5 +1,5 @@
@import '../../../../assets/styles/variables';
-//@import url('https://fonts.googleapis.com/css?family=Open+Sans');
+@import '../../../../assets/styles/mixins';
@ng2-shadow-gray: #f8f8f8;
@ng2-light-gray: #eaeaea;
@ng2-medium-gray: #d2d2d2;
@@ -36,7 +36,7 @@
/deep/ .tab {
padding: 12px;
flex: 1;
- font-weight:bold;
+ font-family: @font-opensans-regular;
&.active {
color:#009fdb;
@@ -44,6 +44,7 @@
border-top: solid 4px #009fdb;
background-color: white;
padding-top:9px;
+ font-family: @font-opensans-medium;
}
.tab-indication {
@@ -129,8 +130,12 @@
flex: none;
padding: 8px 20px 0;
font-size: 14px;
- font-weight:bold;
line-height:30px;
+ font-family: @font-opensans-regular;
+
+ &.active {
+ font-family: @font-opensans-medium;
+ }
}
}
@@ -146,8 +151,6 @@
background-color: #fffefe;
box-shadow: 0px 1px 0.99px 0.01px rgba(34, 31, 31, 0.15);
border-bottom: #d2d2d2 solid 1px;
- color:#009fdb;
- font-weight:bold;
font-size:14px;
text-align:left;
flex:0 0 auto;
@@ -155,6 +158,8 @@
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
+ .a_13_r;
+ text-transform: uppercase;
&.hierarchy-header {
padding-left:20px;
diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts
index 6782b72fa2..82754f13f0 100644
--- a/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts
+++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts
@@ -105,7 +105,7 @@ export class PropertiesAssignmentComponent {
});
this.loadingInputs = false;
- });
+ }, error => {}); //ignore error
this.componentServiceNg2
.getComponentResourceInstances(this.component)
.subscribe(response => {
@@ -120,7 +120,7 @@ export class PropertiesAssignmentComponent {
this.loadingProperties = false;
}
this.selectFirstInstanceByDefault();
- });
+ }, error => {}); //ignore error
};
@@ -159,7 +159,7 @@ export class PropertiesAssignmentComponent {
this.processInstancePropertiesResponse(instanceBePropertiesMap, true);
this.loadingProperties = false;
- });
+ }, error => {}); //ignore error
} else {
this.componentInstanceServiceNg2
.getComponentInstanceProperties(this.component, resourceInstance.uniqueId)
@@ -167,7 +167,7 @@ export class PropertiesAssignmentComponent {
instanceBePropertiesMap[resourceInstance.uniqueId] = response;
this.processInstancePropertiesResponse(instanceBePropertiesMap, false);
this.loadingProperties = false;
- });
+ }, error => {}); //ignore error
}
if(resourceInstance.componentName === "vnfConfiguration") {
@@ -203,16 +203,16 @@ export class PropertiesAssignmentComponent {
this.componentInstanceServiceNg2
.updateInstanceInput(this.component, this.selectedInstanceData.uniqueId, inputToUpdate)
.subscribe(response => {
- console.log("update resource instance input and got this response: ", response);
- })
+ console.log("Update resource instance input response: ", response);
+ }, error => {}); //ignore error
}
else {
let propertyBe = new PropertyBEModel(event);
this.componentInstanceServiceNg2
.updateInstanceProperty(this.component, this.selectedInstanceData.uniqueId, propertyBe)
.subscribe(response => {
- console.log("updated resource instance property and got this response: ", response);
- });
+ console.log("Update resource instance property response: ", response);
+ }, error => {}); //ignore error
console.log(event);
}
@@ -226,7 +226,7 @@ export class PropertiesAssignmentComponent {
.updateComponentInput(this.component, inputToUpdate)
.subscribe(response => {
console.log("updated the component input and got this response: ", response);
- })
+ }, error => {}); //ignore error
};
@@ -322,7 +322,7 @@ export class PropertiesAssignmentComponent {
this.inputs.push(newInput);
this.updatePropertyValueAfterDeclare(newInput);
});
- });
+ }, error => {}); //ignore error
};
@@ -373,7 +373,7 @@ export class PropertiesAssignmentComponent {
// this.propertiesService.undoDisableRelatedProperties(propToEnable, response.inputPath);
// }
// }
- });
+ }, error => {}); //ignore error
};
@@ -391,7 +391,7 @@ export class PropertiesAssignmentComponent {
this.renderer.invokeElementMethod(this.hierarchyNavTabs, 'triggerTabChange', ['Composition']);
this.propertiesNavigationData = [];
this.displayClearSearch = true;
- });
+ }, error => {}); //ignore error
};
diff --git a/catalog-ui/src/app/ng2/pages/properties-assignment/properties.utils.ts b/catalog-ui/src/app/ng2/pages/properties-assignment/properties.utils.ts
index a04d23a16a..d8d991d218 100644
--- a/catalog-ui/src/app/ng2/pages/properties-assignment/properties.utils.ts
+++ b/catalog-ui/src/app/ng2/pages/properties-assignment/properties.utils.ts
@@ -44,9 +44,7 @@ export class PropertiesUtils {
let propertyFeArray: Array<PropertyFEModel> = [];
_.forEach(properties, (property: PropertyBEModel) => {
- if (!this.dataTypeService.getDataTypeByTypeName(property.type)) { // if type not exist in data types remove property from list
- console.log("ERROR: missing type " + property.type + " in dataTypes , of property ", property);
- } else {
+ if (this.dataTypeService.getDataTypeByTypeName(property.type)) { // if type not exist in data types remove property from list
let newFEProp: PropertyFEModel = new PropertyFEModel(property); //Convert property to FE
diff --git a/catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts b/catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts
index 0c499facff..27de59de82 100644
--- a/catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts
+++ b/catalog-ui/src/app/ng2/services/component-instance-services/component-instance.service.ts
@@ -25,14 +25,14 @@ import {sdc2Config} from "../../../../main";
import {PropertyBEModel} from "app/models";
import {CommonUtils} from "app/utils";
import {Component, ComponentInstance, InputModel} from "app/models";
-import {InterceptorService} from "ng2-interceptors/index";
+import { HttpService } from '../http.service';
@Injectable()
export class ComponentInstanceServiceNg2 {
protected baseUrl;
- constructor(private http: InterceptorService) {
+ constructor(private http: HttpService) {
this.baseUrl = sdc2Config.api.root + sdc2Config.api.component_api_root;
}
diff --git a/catalog-ui/src/app/ng2/services/component-services/component.service.ts b/catalog-ui/src/app/ng2/services/component-services/component.service.ts
index cd593d5e3e..c648711d5d 100644
--- a/catalog-ui/src/app/ng2/services/component-services/component.service.ts
+++ b/catalog-ui/src/app/ng2/services/component-services/component.service.ts
@@ -30,8 +30,8 @@ import {ComponentGenericResponse} from "../responses/component-generic-response"
import {sdc2Config} from "../../../../main";
import {InstanceBePropertiesMap} from "../../../models/properties-inputs/property-fe-map";
import {API_QUERY_PARAMS} from "app/utils";
-import {ComponentType, ServerTypeUrl} from "../../../utils/constants";
-import {InterceptorService} from "ng2-interceptors/index";
+import { ComponentType, ServerTypeUrl } from "../../../utils/constants";
+import { HttpService } from '../http.service';
declare var angular:angular.IAngularStatic;
@@ -40,7 +40,7 @@ export class ComponentServiceNg2 {
protected baseUrl;
- constructor(private http:InterceptorService) {
+ constructor(private http:HttpService) {
this.baseUrl = sdc2Config.api.root + sdc2Config.api.component_api_root;
}
@@ -54,7 +54,7 @@ export class ComponentServiceNg2 {
return this.http.get(this.baseUrl + this.getServerTypeUrl(componentType) + componentId + '/filteredDataByParams', {search: params})
.map((res:Response) => {
return new ComponentGenericResponse().deserialize(res.json());
- }).do(error => console.log('server data:', error));
+ });
}
private getServerTypeUrl = (componentType:string):string => {
diff --git a/catalog-ui/src/app/ng2/services/component-services/service.service.ts b/catalog-ui/src/app/ng2/services/component-services/service.service.ts
index 1f5de18c04..ec912bbcf5 100644
--- a/catalog-ui/src/app/ng2/services/component-services/service.service.ts
+++ b/catalog-ui/src/app/ng2/services/component-services/service.service.ts
@@ -26,7 +26,7 @@ import { Response } from '@angular/http';
import {Service} from "app/models";
import { downgradeInjectable } from '@angular/upgrade/static';
import {sdc2Config} from "../../../../main";
-import {InterceptorService} from "ng2-interceptors/index";
+import { HttpService } from '../http.service';
@Injectable()
@@ -34,7 +34,7 @@ export class ServiceServiceNg2 {
protected baseUrl = "";
- constructor(private http: InterceptorService) {
+ constructor(private http: HttpService) {
this.baseUrl = sdc2Config.api.root + sdc2Config.api.component_api_root;
}
diff --git a/catalog-ui/src/app/ng2/services/data-type.service.ts b/catalog-ui/src/app/ng2/services/data-type.service.ts
index 48d32b7e69..30c02a4141 100644
--- a/catalog-ui/src/app/ng2/services/data-type.service.ts
+++ b/catalog-ui/src/app/ng2/services/data-type.service.ts
@@ -38,12 +38,14 @@ export class DataTypeService {
}
public getDataTypeByTypeName(typeName: string): DataTypeModel {
+ if (!this.dataTypes[typeName]) console.log("MISSING Datatype: " + typeName);
return this.dataTypes[typeName];
}
public getDerivedDataTypeProperties(dataTypeObj: DataTypeModel, propertiesArray: Array<DerivedFEProperty>, parentName: string) {
//push all child properties to array
+ if (!dataTypeObj) return;
if (dataTypeObj.properties) {
dataTypeObj.properties.forEach((derivedProperty) => {
if(dataTypeObj.name !== PROPERTY_DATA.OPENECOMP_ROOT || derivedProperty.name !== PROPERTY_DATA.SUPPLEMENTAL_DATA){//The requirement is to not display the property supplemental_data
diff --git a/catalog-ui/src/app/ng2/services/http.interceptor.service.ts b/catalog-ui/src/app/ng2/services/http.interceptor.service.ts
deleted file mode 100644
index c90bfd2848..0000000000
--- a/catalog-ui/src/app/ng2/services/http.interceptor.service.ts
+++ /dev/null
@@ -1,162 +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=========================================================
- */
-
-import 'rxjs/add/operator/map';
-import 'rxjs/add/operator/toPromise';
-import 'rxjs/Rx';
-import {sdc2Config} from './../../../main';
-import {Interceptor, InterceptedRequest, InterceptedResponse} from 'ng2-interceptors';
-import {SharingService} from "../../services/sharing-service";
-import {ReflectiveInjector} from '@angular/core';
-import {Cookie2Service} from "./cookie.service";
-import {UUID} from "angular2-uuid";
-import {Dictionary} from "../../utils/dictionary/dictionary";
-import {SEVERITY} from "../../utils/constants";
-import {IServerMessageModalModel} from "../../view-models/modals/message-modal/message-server-modal/server-message-modal-view-model";
-
-
-export class HttpInterceptor implements Interceptor {
-
- private cookieService:Cookie2Service;
- private sharingService:SharingService;
-
- constructor() {
- let injector = ReflectiveInjector.resolveAndCreate([Cookie2Service, SharingService]);
- this.cookieService = injector.get(Cookie2Service);
- this.sharingService = injector.get(SharingService);
- }
-
- public interceptBefore(request:InterceptedRequest):InterceptedRequest {
- /**
- * For every request to the server, that the service id, or resource id is sent in the URL, need to pass UUID in the header.
- * Check if the unique id exists in uuidMap, and if so get the UUID and add it to the header.
- */
- request.options.headers.append(this.cookieService.getUserIdSuffix(), this.cookieService.getUserId());
- request.options.withCredentials = true;
- var uuidValue = this.getUuidValue(request.url);
- if (uuidValue != '') {
- request.options.headers.set('X-ECOMP-ServiceID', uuidValue);
- }
- request.options.headers.set('X-ECOMP-RequestID', UUID.UUID());
- return request;
- }
-
- public interceptAfter(response:InterceptedResponse):InterceptedResponse {
-
- if (response.response.status !== 200 && response.response.status !== 201) {
- this.responseError(response.response.json());
- //console.log("Error from BE:",response);
- }
- return response;
- }
-
- private getUuidValue = (url:string):string => {
- let map:Dictionary<string, string> = this.sharingService.getUuidMap();
- if (map && url.indexOf(sdc2Config.api.root) > 0) {
- map.forEach((key:string) => {
- if (url.indexOf(key) !== -1) {
- return this.sharingService.getUuidValue(key);
- }
- });
- }
- return '';
- };
-
- public formatMessageArrays = (message:string, variables:Array<string>)=> {
- return message.replace(/\[%(\d+)\]/g, function (_, m) {
- let tmp = [];
- let list = variables[--m].split(";");
- list.forEach(function (item) {
- tmp.push("<li>" + item + "</li>");
- });
- return "<ul>" + tmp.join("") + "</ul>";
- });
- };
-
- public responseError = (rejection:any)=> {
-
- let text:string;
- let variables;
- let messageId:string = "";
- let isKnownException = false;
-
- if (rejection && rejection.serviceException) {
- text = rejection.serviceException.text;
- variables = rejection.serviceException.variables;
- messageId = rejection.serviceException.messageId;
- isKnownException = true;
- } else if (rejection && rejection.requestError && rejection.requestError.serviceException) {
- text = rejection.requestError.serviceException.text;
- variables = rejection.requestError.serviceException.variables;
- messageId = rejection.requestError.serviceException.messageId;
- isKnownException = true;
- } else if (rejection && rejection.requestError && rejection.requestError.policyException) {
- text = rejection.requestError.policyException.text;
- variables = rejection.requestError.policyException.variables;
- messageId = rejection.requestError.policyException.messageId;
- isKnownException = true;
- } else if (rejection) {
- text = 'Wrong error format from server';
- console.error(text);
- isKnownException = false;
- }
-
- let data:IServerMessageModalModel;
- if (isKnownException) {
- // Remove the "Error: " text at the begining
- if (text.trim().indexOf("Error:") === 0) {
- text = text.replace("Error:", "").trim();
- }
-
- //mshitrit DE199895 bug fix
- let count:number = 0;
- variables.forEach(function (item) {
- variables[count] = item ? item.replace('<', '&lt').replace('>', '&gt') : '';
- count++;
- });
-
- // Format the message in case has array to <ul><li>
- text = this.formatMessageArrays(text, variables);
-
- // Format the message %1 %2
- text = text.format(variables);
-
- // Need to inject the MessageService manually to prevent circular dependencies (because MessageService use $templateCache that use $http).
- data = {
- title: 'Error',
- message: text,
- messageId: messageId,
- status: rejection.status,
- severity: SEVERITY.ERROR
- };
- } else {
- // Need to inject the MessageService manually to prevent circular dependencies (because MessageService use $templateCache that use $http).
- data = {
- title: 'Error',
- message: rejection.status !== -1 ? rejection.statusText : "Error getting response from server",
- messageId: messageId,
- status: rejection.status,
- severity: SEVERITY.ERROR
- };
- }
-
- console.error('ERROR data',data);
- }
-}
diff --git a/catalog-ui/src/app/ng2/services/http.service.ts b/catalog-ui/src/app/ng2/services/http.service.ts
index 5cd5a10000..21fe09023a 100644
--- a/catalog-ui/src/app/ng2/services/http.service.ts
+++ b/catalog-ui/src/app/ng2/services/http.service.ts
@@ -24,14 +24,18 @@ import {Observable} from 'rxjs/Observable';
import {UUID} from 'angular2-uuid';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
+import 'rxjs/add/observable/throw';
import {Dictionary} from "../../utils/dictionary/dictionary";
import {SharingService, CookieService} from "app/services";
import {sdc2Config} from './../../../main';
+import { ModalService } from "app/ng2/services/modal.service";
+import { ServerErrorResponse } from "app/models";
+import { ErrorMessageComponent } from 'app/ng2/components/modal/error-message/error-message.component';
@Injectable()
export class HttpService extends Http {
- constructor(backend:XHRBackend, options:RequestOptions, private sharingService:SharingService, private cookieService: CookieService) {
+ constructor(backend: XHRBackend, options: RequestOptions, private sharingService: SharingService, private cookieService: CookieService, private modalService: ModalService) {
super(backend, options);
this._defaultOptions.withCredentials = true;
this._defaultOptions.headers.append(cookieService.getUserIdSuffix(), cookieService.getUserId());
@@ -64,7 +68,7 @@ export class HttpService extends Http {
}
request.headers.set('X-ECOMP-RequestID', UUID.UUID());
}
- return super.request(request, options).catch(this.catchAuthError(this));
+ return super.request(request, options).catch((err) => this.catchError(err));
}
private getUuidValue = (url: string) :string => {
@@ -79,15 +83,14 @@ export class HttpService extends Http {
return '';
}
- private catchAuthError(self:HttpService) {
- // we have to pass HttpService's own instance here as `self`
- return (res:Response) => {
- console.log(res);
- if (res.status === 401 || res.status === 403) {
- // if not authenticated
- console.log(res);
- }
- return Observable.throw(res);
- };
- }
+ private catchError = (response: Response): Observable<any> => {
+
+ let modalInstance = this.modalService.createErrorModal("OK");
+ let errorResponse: ServerErrorResponse = new ServerErrorResponse(response);
+ this.modalService.addDynamicContentToModal(modalInstance, ErrorMessageComponent, errorResponse);
+ modalInstance.instance.open();
+
+ return Observable.throw(response);
+ };
+
}
diff --git a/catalog-ui/src/app/ng2/services/modal.service.ts b/catalog-ui/src/app/ng2/services/modal.service.ts
index 32192f40c2..65ff870769 100644
--- a/catalog-ui/src/app/ng2/services/modal.service.ts
+++ b/catalog-ui/src/app/ng2/services/modal.service.ts
@@ -11,10 +11,10 @@ export class ModalService {
constructor(private componentFactoryResolver: ComponentFactoryResolver, private applicationRef: ApplicationRef) { }
- /* Shortcut method to open a simple modal with title, message, and close button that simply closes the modal. */
+ /* Shortcut method to open an alert modal with title, message, and close button that simply closes the modal. */
public openAlertModal(title: string, message: string, closeButtonText?:string) {
let closeButton: ButtonModel = new ButtonModel(closeButtonText || 'Close', 'grey', this.closeCurrentModal);
- let modalModel: ModalModel = new ModalModel('sm', title, message, [closeButton]);
+ let modalModel: ModalModel = new ModalModel('sm', title, message, [closeButton], 'alert');
this.createCustomModal(modalModel).instance.open();
}
@@ -22,19 +22,28 @@ export class ModalService {
/**
* Shortcut method to open a basic modal with title, message, and an action button with callback, as well as close button.
* NOTE: To close the modal from within the callback, use modalService.closeCurrentModal() //if you run into zone issues with callbacks see:https://stackoverflow.com/questions/36566698/how-to-dynamically-create-bootstrap-modals-as-angular2-components
+ * NOTE: To add dynamic content to the modal, use modalService.addDynamicContentToModal(). First param is the return value of this function -- componentRef<ModalComponent>.
* @param title Heading for modal
* @param message Message for modal
* @param actionButtonText Blue call to action button
* @param actionButtonCallback function to invoke when button is clicked
* @param cancelButtonText text for close/cancel button
*/
- public openActionModal = (title:string, message:string, actionButtonText:string, actionButtonCallback:Function, cancelButtonText:string) => {
+ public createActionModal = (title: string, message: string, actionButtonText: string, actionButtonCallback: Function, cancelButtonText: string): ComponentRef<ModalComponent> => {
let actionButton: ButtonModel = new ButtonModel(actionButtonText, 'blue', actionButtonCallback);
let cancelButton: ButtonModel = new ButtonModel(cancelButtonText, 'grey', this.closeCurrentModal);
let modalModel: ModalModel = new ModalModel('sm', title, message, [actionButton, cancelButton]);
- this.createCustomModal(modalModel).instance.open();
+ let modalInstance: ComponentRef<ModalComponent> = this.createCustomModal(modalModel);
+ return modalInstance;
+ }
+
+
+ public createErrorModal = (closeButtonText?: string, errorMessage?: string):ComponentRef<ModalComponent> => {
+ let closeButton: ButtonModel = new ButtonModel(closeButtonText || 'Close', 'grey', this.closeCurrentModal);
+ let modalModel: ModalModel = new ModalModel('sm', 'Error', errorMessage, [closeButton], 'error');
+ let modalInstance: ComponentRef<ModalComponent> = this.createCustomModal(modalModel);
+ return modalInstance;
}
-
/* Use this method to create a modal with title, message, and completely custom buttons. Use response.instance.open() to open */
public createCustomModal = (customModalData: ModalModel): ComponentRef<ModalComponent> => {
@@ -53,6 +62,14 @@ export class ModalService {
}
+ public addDynamicContentToModal = (modalInstance: ComponentRef<ModalComponent>, dynamicComponentType: Type<any>, dynamicComponentInput: any) => {
+
+ let dynamicContent = this.createDynamicComponent(dynamicComponentType, modalInstance.instance.dynamicContentContainer);
+ dynamicContent.instance.input = dynamicComponentInput;
+ modalInstance.instance.dynamicContent = dynamicContent;
+ return modalInstance;
+ }
+
//Creates a component dynamically (aka during runtime). If a view container is not specified, it will append the new component to the app root.
//To subscribe to an event from invoking component: componentRef.instance.clicked.subscribe((m) => console.log(m.name));
private createDynamicComponent<T>(componentType: Type<T>, viewContainerRef?:ViewContainerRef): ComponentRef<any> {
diff --git a/catalog-ui/src/app/services/event-listener-service.ts b/catalog-ui/src/app/services/event-listener-service.ts
index 1c796230c6..96f9e17641 100644
--- a/catalog-ui/src/app/services/event-listener-service.ts
+++ b/catalog-ui/src/app/services/event-listener-service.ts
@@ -48,7 +48,7 @@ export class EventListenerService implements IEventListenerService {
// Only insert the callback if the callback is different from existing callbacks.
for (let i = 0; i < callbacks.length; i++) {
- if (callbacks[i].toString() === callback.toString()) {
+ if (callbacks[i].callback.toString() === callback.toString()) {
return; // Do not add this callback.
}
}
diff --git a/catalog-ui/src/app/utils/constants.ts b/catalog-ui/src/app/utils/constants.ts
index ffdf6fdaa2..6ec6a7762b 100644
--- a/catalog-ui/src/app/utils/constants.ts
+++ b/catalog-ui/src/app/utils/constants.ts
@@ -167,6 +167,12 @@ export class ModalType {
static ALERT = 'alert';
}
+export class ServerErrors {
+ static ERROR_TITLE = 'Error';
+ static DEFAULT_ERROR = 'Error getting response from server';
+ static MESSAGE_ERROR = 'Wrong error format from server';
+}
+
export class GraphColors {
public static NOT_CERTIFIED_LINK = 'rgb(218,31,61)';
public static VL_LINK = 'rgb(216,216,216)';
diff --git a/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts b/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts
index 3f0838cabc..fa027296d6 100644
--- a/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts
+++ b/catalog-ui/src/app/view-models/forms/resource-instance-name-form/resource-instance-name-model.ts
@@ -109,7 +109,8 @@ export class ResourceInstanceNameViewModel {
];
this.$scope.$watch("[forms.editNameForm.$invalid,componentInstanceModel.name,isAlreadyPressed]", (newVal, oldVal) => {
- this.$scope.footerButtons[0].disabled = this.$scope.forms.editNameForm.$invalid || this.$scope.isAlreadyPressed || this.$scope.componentInstanceModel.name === this.$scope.oldName;
+ //if the name is invalid or if user pressed ok and didn't try to change name again or the new name = source name
+ this.$scope.footerButtons[0].disabled = this.$scope.forms.editNameForm.$invalid || (this.$scope.isAlreadyPressed && newVal[1] === oldVal[1]) || this.$scope.componentInstanceModel.name === this.$scope.oldName;
});
}
}
diff --git a/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts
index 37b9b9db9c..f77a29b003 100644
--- a/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts
+++ b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view-model.ts
@@ -22,6 +22,7 @@
import {IUserProperties} from "app/models";
import {MenuItemGroup, MenuItem} from "app/utils";
import {CacheService} from "app/services";
+declare var PunchOutRegistry;
export class BreadcrumbsMenuItem {
key:string;
@@ -48,7 +49,7 @@ export interface IOnboardVendorViewModelScope extends ng.IScope {
topNavRootMenu:MenuItemGroup;
user:IUserProperties;
version:string;
- isLoading: boolean;
+ isLoading:boolean;
}
export class OnboardVendorViewModel {
@@ -66,10 +67,13 @@ export class OnboardVendorViewModel {
this.$scope.isLoading = true;
- $.getScript("/onboarding/punch-outs_en.js", () => {
+ PunchOutRegistry.loadOnBoarding(()=> {
this.$scope.isLoading = false;
});
+ this.initScope();
+ }
+ private initScope = ():void => {
this.$scope.vendorData = {
breadcrumbs: {
selectedKeys: []
@@ -89,6 +93,7 @@ export class OnboardVendorViewModel {
this.$scope.topNavMenuModel = [];
this.$scope.user = this.cacheService.get('user');
+
}
updateBreadcrumbsPath = (selectedKeys:Array<string>):ng.IPromise<boolean> => {
@@ -140,6 +145,7 @@ export class OnboardVendorViewModel {
let topNavRootMenu = topNavMenuModel[0];
let onboardItem = topNavRootMenu.menuItems[topNavRootMenu.selectedIndex];
let originalCallback = onboardItem.callback;
+ //noinspection TypeScriptValidateTypes
onboardItem.callback = (...args) => {
let ret = this.updateBreadcrumbsPath([]);
return originalCallback && originalCallback.apply(undefined, args) || ret;
diff --git a/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view.html b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view.html
index 56a36863e1..eec7c4758d 100644
--- a/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view.html
+++ b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor-view.html
@@ -1,6 +1,6 @@
<div class="sdc-catalog-container">
- <loader ng-init="isLoading=true" data-display="isLoading"></loader>
+ <loader data-display="isLoading"></loader>
<div class="w-sdc-main-container">
<punch-out name="'onboarding/vendor'" data="vendorData" user="user" on-event="onVendorEvent"></punch-out>
</div>
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts b/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts
index f4ce1d8bc4..5d22d65f52 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.ts
@@ -54,7 +54,6 @@ export class ActivityLogViewModel {
this.initScope();
this.$scope.setValidState(true);
this.initSortedTableScope();
- this.$scope.updateSelectedMenuItem();
// Set default sorting
this.$scope.sortBy = 'logDate';
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view-model.ts
index ce7296cf04..312a663e8f 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes-view-model.ts
@@ -53,7 +53,6 @@ export class AttributesViewModel {
private ComponentServiceNg2: ComponentServiceNg2) {
this.initComponentAttributes();
- this.$scope.updateSelectedMenuItem();
}
private initComponentAttributes = () => {
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view-model.ts
index 0e5a5fcd6c..4b9dd6fc00 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view-model.ts
@@ -47,6 +47,7 @@ export interface ICompositionViewModelScope extends IWorkspaceViewModelScope {
onBackgroundClick():void;
setSelectedInstance(componentInstance:ComponentInstance):void;
printScreen():void;
+ isPNF():boolean;
cacheComponentsInstancesFullData:Component;
}
@@ -90,7 +91,6 @@ export class CompositionViewModel {
this.$scope.setValidState(true);
this.initScope();
this.initGraphData();
- this.$scope.updateSelectedMenuItem();
this.registerGraphEvents(this.$scope);
}
@@ -242,7 +242,10 @@ export class CompositionViewModel {
this.$scope.setComponent(this.$scope.currentComponent);
this.$scope.updateSelectedComponent();
};
-
+
+ this.$scope.isPNF = (): boolean => {
+ return this.$scope.selectedComponent.isResource() && (<Resource>this.$scope.selectedComponent).resourceType === ResourceType.PNF;
+ };
this.eventListenerService.registerObserverCallback(EVENTS.ON_CHECKOUT, this.$scope.reload);
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts
index c4c63fae06..f0c8b1d86b 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view-model.ts
@@ -249,7 +249,6 @@ export class ResourceArtifactsViewModel {
this.$scope.isLoading = false;
this.$scope.artifactType = this.artifactsUtils.getArtifactTypeByState(this.$state.current.name);
- this.loadArtifacts();
this.$scope.getTitle = ():string => {
return this.artifactsUtils.getTitle(this.$scope.artifactType, this.$scope.currentComponent);
};
@@ -335,5 +334,7 @@ export class ResourceArtifactsViewModel {
this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_NODE_SELECTED, this.loadArtifacts);
this.eventListenerService.unRegisterObserver(GRAPH_EVENTS.ON_GRAPH_BACKGROUND_CLICKED, this.loadArtifacts);
});
+
+ this.loadArtifacts();
}
}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts
index 6990ad7241..86bc478048 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model.ts
@@ -74,7 +74,6 @@ export class DeploymentArtifactsViewModel {
private ModalsHandler:ModalsHandler,
private ComponentServiceNg2: ComponentServiceNg2) {
this.initScope();
- this.$scope.updateSelectedMenuItem();
}
private initDescriptions = ():void => {
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view-model.ts
index 76be6c1141..feda7fe17f 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/deployment/deployment-view-model.ts
@@ -86,7 +86,6 @@ export class DeploymentViewModel {
this.$scope.setValidState(true);
this.initScope();
this.initGraphData();
- this.$scope.updateSelectedMenuItem();
}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts
index 1852b6a83e..663361cd85 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/distribution/distribution-view-model.ts
@@ -48,7 +48,6 @@ export class DistributionViewModel {
private ModalsHandler:ModalsHandler) {
this.initScope();
this.$scope.setValidState(true);
- this.$scope.updateSelectedMenuItem();
}
private initScope = ():void => {
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts
index 1dc326a7c0..98539d6a3b 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts
@@ -118,7 +118,6 @@ export class GeneralViewModel {
this.initScopeValidation();
this.initScopeMethods();
this.initScope();
- this.$scope.updateSelectedMenuItem();
}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts
index ceaba3c187..b2fd4d68c0 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts-view-model.ts
@@ -65,7 +65,6 @@ export class InformationArtifactsViewModel {
private ModalsHandler:ModalsHandler,
private ComponentServiceNg2: ComponentServiceNg2) {
this.initInformationalArtifacts();
- this.$scope.updateSelectedMenuItem();
}
private initInformationalArtifacts = ():void => {
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts
index 78865ac873..2e871a5f8d 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/inputs/resource-input/resource-inputs-view-model.ts
@@ -45,7 +45,6 @@ export class ResourceInputsViewModel {
constructor(private $scope:IInputsViewModelScope, private $q:ng.IQService, private ModalsHandler:ModalsHandler) {
this.initScope();
- this.$scope.updateSelectedMenuItem();
}
private initScope = ():void => {
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts
index 013a0023f9..00f3347b74 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/inputs/service-input/service-inputs-view-model.ts
@@ -62,7 +62,6 @@ export class ServiceInputsViewModel {
private ModalsHandler:ModalsHandler,
private DataTypesService:DataTypesService) {
this.initScope();
- this.$scope.updateSelectedMenuItem();
this.$scope.isViewOnly = this.$scope.isViewMode();
}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view-model.ts
index f8b29c4a9c..e44ed12c2a 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view-model.ts
@@ -18,130 +18,137 @@
* ============LICENSE_END=========================================================
*/
- 'use strict';
- import {ArtifactType} from "app/utils";
- import {ArtifactGroupModel} from "app/models";
- import {participant} from "app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model";
- import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
- import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response";
- import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service";
+'use strict';
+import {ArtifactType} from "app/utils";
+import {ArtifactGroupModel} from "app/models";
+import {participant} from "app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model";
+import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
+import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response";
+import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service";
+declare var PunchOutRegistry;
- export interface IManagementWorkflowViewModelScope extends IWorkspaceViewModelScope {
- vendorModel:VendorModel;
- }
+export interface IManagementWorkflowViewModelScope extends IWorkspaceViewModelScope {
+ vendorModel:VendorModel;
+ isLoading: boolean;
+}
- export class VendorModel {
- artifacts: ArtifactGroupModel;
- serviceID: string;
- readonly: boolean;
- sessionID: string;
- requestID: string;
- diagramType: string;
- participants:Array<participant>;
+export class VendorModel {
+ artifacts:ArtifactGroupModel;
+ serviceID:string;
+ readonly:boolean;
+ sessionID:string;
+ requestID:string;
+ diagramType:string;
+ participants:Array<participant>;
- constructor(artifacts: ArtifactGroupModel, serviceID:string, readonly:boolean, sessionID:string,
- requestID:string, diagramType:string, participants:Array<participant>){
- this.artifacts = artifacts;
- this.serviceID = serviceID;
- this.readonly = readonly;
- this.sessionID = sessionID;
- this.requestID = requestID;
- this.diagramType = diagramType;
- this.participants = participants;
- }
+ constructor(artifacts:ArtifactGroupModel, serviceID:string, readonly:boolean, sessionID:string,
+ requestID:string, diagramType:string, participants:Array<participant>) {
+ this.artifacts = artifacts;
+ this.serviceID = serviceID;
+ this.readonly = readonly;
+ this.sessionID = sessionID;
+ this.requestID = requestID;
+ this.diagramType = diagramType;
+ this.participants = participants;
}
+}
+
+export class ManagementWorkflowViewModel {
- export class ManagementWorkflowViewModel {
+ static '$inject' = [
+ '$scope',
+ 'uuid4',
+ 'ComponentServiceNg2'
+ ];
- static '$inject' = [
- '$scope',
- 'uuid4',
- 'ComponentServiceNg2'
- ];
+ constructor(private $scope:IManagementWorkflowViewModelScope,
+ private uuid4:any,
+ private ComponentServiceNg2:ComponentServiceNg2) {
- constructor(private $scope:IManagementWorkflowViewModelScope,
- private uuid4:any,
- private ComponentServiceNg2: ComponentServiceNg2) {
+ this.$scope.isLoading = true;
+ PunchOutRegistry.loadOnBoarding(()=> {
+ this.$scope.isLoading = false;
this.initInformationalArtifacts();
- this.$scope.updateSelectedMenuItem();
- }
+ });
+ }
- private initInformationalArtifacts = ():void => {
- if(!this.$scope.component.artifacts) {
- this.$scope.isLoading = true;
- this.ComponentServiceNg2.getComponentInformationalArtifacts(this.$scope.component).subscribe((response:ComponentGenericResponse) => {
- this.$scope.component.artifacts = response.artifacts;
- this.initScope();
- this.$scope.isLoading = false;
- });
- } else {
+ private initInformationalArtifacts = ():void => {
+ if (!this.$scope.component.artifacts) {
+ this.$scope.isLoading = true;
+ this.ComponentServiceNg2.getComponentInformationalArtifacts(this.$scope.component).subscribe((response:ComponentGenericResponse) => {
+ this.$scope.component.artifacts = response.artifacts;
this.initScope();
- }
+ this.$scope.isLoading = false;
+ });
+ } else {
+ this.initScope();
}
+ }
- private static getParticipants():Array<participant> {
- return [
- {
- "id": "1",
- "name": "Customer"},
- {
- "id": "2",
- "name": "CCD"
- },
- {
- "id": "3",
- "name": "Infrastructure"
- },
- {
- "id": "4",
- "name": "MSO"
- },
- {
- "id": "5",
- "name": "SDN-C"
- },
- {
- "id": "6",
- "name": "A&AI"
- },
- {
- "id": "7",
- "name": "APP-C"
- },
- {
- "id": "8",
- "name": "Cloud"
- },
- {
- "id": "9",
- "name": "DCAE"
- },
- {
- "id": "10",
- "name": "ALTS"
- },
- {
- "id": "11",
- "name": "VF"
- }
- ]
- }
+ private static getParticipants():Array<participant> {
+ return [
+ {
+ "id": "1",
+ "name": "Customer"
+ },
+ {
+ "id": "2",
+ "name": "CCD"
+ },
+ {
+ "id": "3",
+ "name": "Infrastructure"
+ },
+ {
+ "id": "4",
+ "name": "MSO"
+ },
+ {
+ "id": "5",
+ "name": "SDN-C"
+ },
+ {
+ "id": "6",
+ "name": "A&AI"
+ },
+ {
+ "id": "7",
+ "name": "APP-C"
+ },
+ {
+ "id": "8",
+ "name": "Cloud"
+ },
+ {
+ "id": "9",
+ "name": "DCAE"
+ },
+ {
+ "id": "10",
+ "name": "ALTS"
+ },
+ {
+ "id": "11",
+ "name": "VF"
+ }
+ ]
+ }
- private initScope():void {
- this.$scope.vendorModel = new VendorModel(
- this.$scope.component.artifacts.filteredByType(ArtifactType.THIRD_PARTY_RESERVED_TYPES.WORKFLOW),
- this.$scope.component.uniqueId,
- this.$scope.isViewMode(),
- this.$scope.user.userId,
- this.uuid4.generate(),
- ArtifactType.THIRD_PARTY_RESERVED_TYPES.WORKFLOW,
- ManagementWorkflowViewModel.getParticipants()
- );
+ private initScope():void {
+ this.$scope.vendorModel = new VendorModel(
+ this.$scope.component.artifacts.filteredByType(ArtifactType.THIRD_PARTY_RESERVED_TYPES.WORKFLOW),
+ this.$scope.component.uniqueId,
+ this.$scope.isViewMode(),
+ this.$scope.user.userId,
+ this.uuid4.generate(),
+ ArtifactType.THIRD_PARTY_RESERVED_TYPES.WORKFLOW,
+ ManagementWorkflowViewModel.getParticipants()
+ );
- this.$scope.thirdParty = true;
- this.$scope.setValidState(true);
- }
+ this.$scope.thirdParty = true;
+ this.$scope.setValidState(true);
}
+}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view.html b/catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view.html
index bd196daec8..df570ccdca 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/management-workflow/management-workflow-view.html
@@ -1,3 +1,4 @@
-<div class="workspace-management-workflow">
- <punch-out name="'sequence-diagram'" data="vendorModel" user="user" on-event="onVendorEvent"></punch-out>
+<loader data-display="isLoading"></loader>
+<div class="workspace-management-workflow" ng-if="vendorModel">
+ <punch-out name="'sequence-diagram'" data="vendorModel" user="user" on-event="onVendorEvent"></punch-out>
</div>
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts
index 6c7666d28c..488e4c774d 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view-model.ts
@@ -25,9 +25,11 @@ import {ResourceType, ArtifactType} from "app/utils";
import {ComponentInstance} from "app/models";
import {ComponentGenericResponse} from "../../../../ng2/services/responses/component-generic-response";
import {ComponentServiceNg2} from "../../../../ng2/services/component-services/component.service";
+declare var PunchOutRegistry;
export interface INetworkCallFlowViewModelScope extends IWorkspaceViewModelScope {
vendorMessageModel:VendorModel;
+ isLoading: boolean;
}
export class participant {
@@ -53,8 +55,12 @@ export class NetworkCallFlowViewModel {
private uuid4:any,
private ComponentServiceNg2: ComponentServiceNg2) {
- this.initComponentInstancesAndInformationalArtifacts();
- this.$scope.updateSelectedMenuItem();
+ this.$scope.isLoading = true;
+
+ PunchOutRegistry.loadOnBoarding(()=> {
+ this.$scope.isLoading = false;
+ this.initComponentInstancesAndInformationalArtifacts();
+ });
}
private getVFParticipantsFromInstances(instances:Array<ComponentInstance>):Array<participant> {
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html b/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html
index 6ce3e8e2b7..bc2d0643e0 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/network-call-flow/network-call-flow-view.html
@@ -1,3 +1,4 @@
-<div class="workspace-network-call-flow">
+<loader data-display="isLoading"></loader>
+<div ng-if="vendorMessageModel" class="workspace-network-call-flow">
<punch-out name="'sequence-diagram'" data="vendorMessageModel" user="user" on-event="onVendorEvent"></punch-out>
</div>
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view-model.ts
index c9f2d0725f..3c9c7e9e4b 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/properties/properties-view-model.ts
@@ -52,7 +52,6 @@ export class PropertiesViewModel {
private ModalsHandler:ModalsHandler,
private ComponentServiceNg2:ComponentServiceNg2) {
this.initComponentProperties();
- this.$scope.updateSelectedMenuItem();
}
private initComponentProperties = ():void => {
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts
index c02900a413..b6cbf65cf0 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities-view-model.ts
@@ -67,7 +67,6 @@ export class ReqAndCapabilitiesViewModel {
private ComponentServiceNg2: ComponentServiceNg2) {
this.initCapabilitiesAndRequirements();
- this.$scope.updateSelectedMenuItem();
}
private initCapabilitiesAndRequirements = (): void => {
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts
index 5f724c48fd..77b5ab74eb 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model.ts
@@ -50,7 +50,6 @@ export class ToscaArtifactsViewModel {
private $filter:ng.IFilterService,
private ComponentServiceNg2:ComponentServiceNg2) {
this.initToscaArtifacts();
- this.$scope.updateSelectedMenuItem();
}
private initToscaArtifacts = (): void => {
diff --git a/catalog-ui/src/app/view-models/workspace/workspace-view-model.ts b/catalog-ui/src/app/view-models/workspace/workspace-view-model.ts
index f529e79fa7..a3af8ca68e 100644
--- a/catalog-ui/src/app/view-models/workspace/workspace-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/workspace-view-model.ts
@@ -87,7 +87,7 @@ export interface IWorkspaceViewModelScope extends ng.IScope {
getLatestVersion():void;
getStatus():string;
showLifecycleIcon():boolean;
- updateSelectedMenuItem():void;
+ updateSelectedMenuItem(state:string):void;
uploadFileChangedInGeneralTab():void;
updateMenuComponentName(ComponentName:string):void;
getTabTitle():string;
@@ -136,6 +136,7 @@ export class WorkspaceViewModel {
this.initScope();
this.initAfterScope();
+ this.$scope.updateSelectedMenuItem(this.$state.current.name);
}
private role:string;
@@ -216,6 +217,7 @@ export class WorkspaceViewModel {
this.$scope.onMenuItemPressed = (state:string):ng.IPromise<boolean> => {
let deferred = this.$q.defer();
let goToState = ():void => {
+ this.$scope.updateSelectedMenuItem(state);
this.$state.go(state, {
id: this.$scope.component.uniqueId,
type: this.$scope.component.componentType.toLowerCase(),
@@ -613,9 +615,11 @@ export class WorkspaceViewModel {
return result;
};
- this.$scope.updateSelectedMenuItem = ():void => {
+ this.$scope.updateSelectedMenuItem = (state:string):void => {
+ let stateArray:Array<string> = state.split('.');
+ let stateWithoutInternalNavigate:string = stateArray[0] + '.' + stateArray[1];
let selectedItem:MenuItem = _.find(this.$scope.leftBarTabs.menuItems, (item:MenuItem) => {
- return item.state === this.$state.current.name;
+ return _.startsWith(item.state, stateWithoutInternalNavigate);
});
this.$scope.leftBarTabs.selectedIndex = selectedItem ? this.$scope.leftBarTabs.menuItems.indexOf(selectedItem) : 0;
};
diff --git a/catalog-ui/src/assets/styles/app.less b/catalog-ui/src/assets/styles/app.less
index fde4cc8888..c19ace5823 100644
--- a/catalog-ui/src/assets/styles/app.less
+++ b/catalog-ui/src/assets/styles/app.less
@@ -8,6 +8,7 @@
@import 'mixins.less';
@import 'mixins_old.less';
@import 'global.less';
+@import '../../../node_modules/sdc-ui/css/style.css';
@import 'sprite-old.less';
@import 'sprite.less';
@@ -33,7 +34,6 @@
@import 'tooltips.less';
@import 'welcome-sprite.less';
@import 'welcome-style.less';
-@import 'sdc-ui.css';
@import 'notification-template.less';
// Less insides specific files.
diff --git a/catalog-ui/src/assets/styles/sdc-ui.css b/catalog-ui/src/assets/styles/sdc-ui.css
deleted file mode 100644
index ad96e7762a..0000000000
--- a/catalog-ui/src/assets/styles/sdc-ui.css
+++ /dev/null
@@ -1,361 +0,0 @@
-@charset "UTF-8";
-/* Colors */
-.sdc-bc-blue {
- background-color: #009fdb; }
-
-.sdc-bc-dark-blue {
- background-color: #0568ae; }
-
-.sdc-bc-light-blue {
- background-color: #71c5e8; }
-
-.sdc-bc-green {
- background-color: #4ca90c; }
-
-.sdc-bc-dark-green {
- background-color: #007a3e; }
-
-.sdc-bc-light-green {
- background-color: #b5bd00; }
-
-.sdc-bc-orange {
- background-color: #ea7400; }
-
-.sdc-bc-yellow {
- background-color: #ffb81c; }
-
-.sdc-bc-dark-purple {
- background-color: #702f8a; }
-
-.sdc-bc-purple {
- background-color: #9063cd; }
-
-.sdc-bc-light-purple {
- background-color: #caa2dd; }
-
-.sdc-bc-black {
- background-color: #000000; }
-
-.sdc-bc-dark-gray {
- background-color: #5a5a5a; }
-
-.sdc-bc-gray {
- background-color: #959595; }
-
-.sdc-bc-light-gray {
- background-color: #d2d2d2; }
-
-.sdc-bc-white {
- background-color: #ffffff; }
-
-/* Prefix */
-/* Value Prefix*/
-/* Box sizing */
-/* Borders & Shadows */
-/* Opacity */
-/* Ellipsis */
-/* Vertical placement of multuple lines of text */
-/* transform-rotate */
-/* transform-translate */
-/* transform-scale */
-/**/
-/**/
-/*body {*/
- /*-webkit-touch-callout: none;*/
- /*-webkit-user-select: none;*/
- /*-moz-user-select: none;*/
- /*-ms-user-select: none;*/
- /*user-select: none; }*/
-
-html {
- font-size: 100%;
- height: 100%; }
-
-body {
- /* scrollbar styling for Internet Explorer */
- scrollbar-face-color: #191919;
- scrollbar-track-color: #191919;
- height: 100%; }
-
-/* scrollbar styling for Google Chrome | Safari | Opera */
-::-webkit-scrollbar {
- width: 8px;
- height: 8px; }
-
-::-webkit-scrollbar-track {
- background-color: transparent;
- border-radius: 10px; }
-
-::-webkit-scrollbar-thumb {
- border-radius: 10px;
- background-color: #d2d2d2;
- border-right: 2px solid #ffffff; }
-
-/* Mozilla Firefox currently doesn't support scrollbar styling */
-ul {
- list-style: none; }
-
-h1, h2, h3, h4, h5, h6, ul {
- margin: 0;
- padding: 0; }
-
-.disabled {
- opacity: 0.7 !important; }
-
-fieldset {
- border: none; }
-
-fieldset label {
- display: inline-block; }
-
-.nav-tabs > li > a:focus,
-.btn:focus,
-.btn:active:focus,
-.btn.active:focus {
- outline: none; }
-
-/* Fonts */
-.text-lowercase {
- text-transform: lowercase; }
-
-.text-uppercase, .heading-3-light, .heading-3, .heading-3-medium {
- text-transform: uppercase; }
-
-.text-capitalize {
- text-transform: capitalize; }
-
-.heading-1 {
- font-weight: 300;
- font-size: 36px; }
-
-.heading-2 {
- font-weight: 300;
- font-size: 24px; }
-
-.heading-3-light {
- font-weight: 300;
- font-size: 20px; }
-
-.heading-3 {
- font-weight: 400;
- font-size: 20px; }
-
-.heading-3-medium {
- font-weight: 600;
- font-size: 20px; }
-
-.heading-4 {
- font-weight: 400;
- font-size: 18px; }
-
-.heading-4-medium {
- font-weight: 600;
- font-size: 18px; }
-
-.heading-5 {
- font-weight: 400;
- font-size: 16px; }
-
-.heading-5-medium, .catalog-tile .catalog-tile-top .catalog-tile-item-name, .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-info .sdc-tile-content-info-item-name {
- font-weight: 400;
- line-height: 16px;
- font-size: 14px; }
-
-.body-1 {
- font-weight: 400;
- font-size: 14px; }
-
-.body-1-medium {
- font-weight: 600;
- font-size: 14px; }
-
-.body-1-light {
- font-weight: 300;
- font-size: 14px; }
-
-.body-2, .catalog-tile .catalog-tile-top .catalog-tile-entity-details .catalog-tile-version-info .catalog-tile-item-version, .catalog-tile .catalog-tile-content .catalog-tile-locking-user-name, .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-info .sdc-tile-content-info-version-info .sdc-tile-content-info-version-info-text, .sdc-tile-catalog .sdc-tile-footer .sdc-tile-footer-text {
- font-weight: 400;
- font-size: 12px; }
-
-.body-2-medium, .catalog-tile .catalog-tile-content {
- font-weight: 600;
- font-size: 13px; }
-
-.body-3 {
- font-weight: 400;
- font-size: 12px; }
-
-.body-3-medium, .catalog-tile .catalog-tile-top .catalog-tile-entity-details .catalog-tile-vendor-name, .catalog-tile.vendor-type .catalog-tile-top .catalog-tile-vsp-count, .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-info .sdc-tile-content-info-vendor-name {
- font-weight: 600;
- font-size: 12px; }
-
-.body-3-light {
- font-weight: 300;
- font-size: 12px; }
-
-.circle-icon-text {
- font-weight: 600;
- font-size: 14px; }
-
-.sdc-icon {
- display: inline-block;
- text-rendering: auto;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
- width: 16px;
- height: 16px; }
-
-.sdc-icon-locked {
- background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='11' height='15' viewBox='0 0 11 15' id='locked_icon'> <metadata><?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?><x:xmpmeta xmlns:x='adobe:ns:meta/' x:xmptk='Adobe XMP Core 5.6-c138 79.159824, 2016/09/14-01:09:01 '> <rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'> <rdf:Description rdf:about=''/> </rdf:RDF></x:xmpmeta><?xpacket end='w'?></metadata><defs> <style> .cls-1 { fill: #959595; fill-rule: evenodd; } </style> </defs> <path id='Shape_77_copy_10' data-name='Shape 77 copy 10' class='cls-1' d='M445,359a16.71,16.71,0,0,0-2.1-.009c-1.945.045-3.195,0.049-3.9,0.009v-5a1.743,1.743,0,0,1,2-2h1a1.743,1.743,0,0,1,2,2v5c0.474,0.063.343-.073,1,0,0.266,0.029,0,.279,0,0v-5a2.726,2.726,0,0,0-3-3h-1.142c-1.72-.125-2.715,1.562-2.858,3,0.088,0.009,0,7.338,0,5h0a1.891,1.891,0,0,0-2,1.689v3.461A1.823,1.823,0,0,0,437.775,366h7.448A1.823,1.823,0,0,0,447,364.15v-3.461A2.018,2.018,0,0,0,445,359Z' transform='translate(-436 -351)'/></svg>");
- background-repeat: no-repeat; }
-
-.sdc-icon-plus {
- background-image: url("data:image/svg+xml;utf8,<?xml version='1.0' encoding='utf-8'?><!-- Generator: Adobe Illustrator 21.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --><svg version='1.1' id='plus_icon' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 19 19' style='enable-background:new 0 0 19 19;' xml:space='preserve'><g><rect y='8' width='19' height='3'/><path id='Rectangle_2139_copy' d='M8,19V0h3v19H8z'/></g></svg>");
- background-repeat: no-repeat; }
-
-.sdc-icon-unlocked {
- background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='11' height='18' viewBox='0 0 11 18' id='unlocked_icon'> <metadata><?xpacket begin='' id='W5M0MpCehiHzreSzNTczkc9d'?><x:xmpmeta xmlns:x='adobe:ns:meta/' x:xmptk='Adobe XMP Core 5.6-c138 79.159824, 2016/09/14-01:09:01 '> <rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'> <rdf:Description rdf:about=''/> </rdf:RDF></x:xmpmeta><?xpacket end='w'?></metadata><defs> <style> .cls-1 { fill: #959595; fill-rule: evenodd; } </style> </defs> <path id='Shape_77_copy_16' data-name='Shape 77 copy 16' class='cls-1' d='M663,358a16.723,16.723,0,0,0-2.1-.009c-1.944.045-3.194,0.049-3.9,0.009v-7a1.743,1.743,0,0,1,2-2h1a1.743,1.743,0,0,1,2,2v2c0.474,0.064.343-.073,1,0,0.266,0.029,0,.279,0,0v-2a2.726,2.726,0,0,0-3-3h-1.142c-1.72-.125-2.715,1.562-2.858,3,0.088,0.009,0,9.338,0,7h0a1.891,1.891,0,0,0-2,1.689v4.461a1.823,1.823,0,0,0,1.775,1.85h7.448A1.823,1.823,0,0,0,665,364.15v-4.461A2.018,2.018,0,0,0,663,358Zm1.05,6.15a0.827,0.827,0,0,1-.8.836H655.8a0.827,0.827,0,0,1-.8-0.836l0-4.15a1.164,1.164,0,0,1,.8-1.147h7.448A1.129,1.129,0,0,1,664,360Z' transform='translate(-654 -348)'/></svg>");
- background-repeat: no-repeat; }
-
-.sdc-icon-vendor {
- background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 53 47' id='vendor_icon'><title>vendor</title><g id='Layer_2' data-name='Layer 2'><g id='vlm_icon' data-name='vlm icon'><path d='M49,7,38.5,7V5.92A5.92,5.92,0,0,0,32.58,0H20.42A5.92,5.92,0,0,0,14.5,5.92V7.15L4,7.2a3.8,3.8,0,0,0-4,3.5V43.5C0,45.4,2,47,4.2,47L49,46.8a3.8,3.8,0,0,0,4-3.5V10.5A3.8,3.8,0,0,0,49,7ZM16.5,5.92A3.92,3.92,0,0,1,20.42,2H32.58A3.92,3.92,0,0,1,36.5,5.92V7.06l-20,.09ZM2,10.8A1.9,1.9,0,0,1,4,9l45-.2a1.9,1.9,0,0,1,2,1.8v8.87L32.94,24.18a6.49,6.49,0,0,0-12.89,0L2,19.51V10.8ZM31,25a4.5,4.5,0,1,1-4.5-4.5A4.5,4.5,0,0,1,31,25ZM49,45,4,45.2A1.9,1.9,0,0,1,2,43.4V21.57l18.13,4.73a6.5,6.5,0,0,0,12.74,0L51,21.53V43.21A1.9,1.9,0,0,1,49,45Z'/></g></g></svg>");
- background-repeat: no-repeat; }
-
-.sdc-icon-vlm {
- background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 45 53'><title>vlm_new_icon</title><g id='Layer_2' data-name='Layer 2'><g id='vlm_icon' data-name='vlm icon'><path d='M41,2a2,2,0,0,1,2,2l.19,45a2,2,0,0,1-2,2H4a2,2,0,0,1-2-2L1.81,4a2,2,0,0,1,2-2H41m-.15-2H4A4.2,4.2,0,0,0,0,4.24L.19,49a4,4,0,0,0,4,4H41a4,4,0,0,0,4-4L44.81,4a4,4,0,0,0-4-4Z'/><rect x='14' y='11' width='17' height='2'/><rect x='14' y='18' width='10' height='2'/><polygon points='20.56 38.85 13.87 33.14 15.16 31.62 20.39 36.08 29.08 26.63 30.55 27.98 20.56 38.85'/></g></g></svg>");
- background-repeat: no-repeat; }
-
-.sdc-icon-vsp {
- background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 59.5 40' id='vsp_icon'><title>vsp_new_icon</title><g id='Layer_2' data-name='Layer 2'><g id='vlm_icon' data-name='vlm icon'><path d='M58.28,30.74c-1.49-1.82-3-2.7-4.67-2.74a8.5,8.5,0,0,0-16.22-2.44,6.93,6.93,0,0,0-4.06.66A7.23,7.23,0,0,0,36.42,40H53.5a6,6,0,0,0,6-6A5.18,5.18,0,0,0,58.28,30.74ZM53.5,38H36.42a5.25,5.25,0,0,1-5.21-5.91,5.32,5.32,0,0,1,3-4.06,5,5,0,0,1,2.21-.53,5.25,5.25,0,0,1,1.35.18l.92.24L39,27A6.5,6.5,0,0,1,51.67,29v1.3l1.17-.2c1-.17,2.17-.17,3.91,2a3.18,3.18,0,0,1,.76,2A4,4,0,0,1,53.5,38Z'/><path d='M49,0,4,.17A3.79,3.79,0,0,0,0,3.69V7.94H0v2H0V36.31C0,38.35,2,40,4.25,40l20.84-.08a1,1,0,0,0,0-1.92L4,38.08a1.89,1.89,0,0,1-2-1.76V10H51v7a1,1,0,0,0,2,0V3.53A3.79,3.79,0,0,0,49,0ZM2,8V3.76A1.89,1.89,0,0,1,4,2l45-.16a1.89,1.89,0,0,1,2,1.76V8Z'/></g></g></svg>");
- background-repeat: no-repeat; }
-
-.svg-icon.purple {
- fill: #9063cd; }
-
-.svg-icon.purple-hover {
- fill: #9063cd; }
- .svg-icon.purple-hover:hover {
- fill: #caa2dd; }
-
-.svg-icon.blue {
- fill: #009fdb; }
-
-.svg-icon.blue-hover {
- fill: #009fdb; }
- .svg-icon.blue-hover:hover {
- fill: #71c5e8; }
-
-.svg-icon.gray {
- fill: #959595; }
-
-.svg-icon.gray-hover {
- fill: #000000; }
- .svg-icon.gray-hover:hover {
- fill: #d2d2d2; }
-
-.svg-icon.black {
- fill: #000000; }
-
-.svg-icon.black-hover {
- fill: #000000; }
- .svg-icon.black-hover:hover {
- fill: #d2d2d2; }
-
-.sdc-tile, .sdc-tile-catalog {
- box-sizing: border-box;
- background-color: #ffffff;
- display: flex;
- flex-direction: column;
- padding: 10px;
- cursor: pointer;
- border: 1px solid #eaeaea;
- -webkit-box-shadow: 0.5px 0.8px 4px 0 rgba(24, 24, 25, 0.05);
- -moz-box-shadow: 0.5px 0.8px 4px 0 rgba(24, 24, 25, 0.05);
- box-shadow: 0.5px 0.8px 4px 0 rgba(24, 24, 25, 0.05); }
- .sdc-tile:active, .sdc-tile-catalog:active {
- border: 1px solid #71c5e8; }
- .sdc-tile:hover, .sdc-tile-catalog:hover {
- box-shadow: 0.3px 5px 12.8px 1.3px rgba(24, 24, 25, 0.15);
- border: 1px solid #d2d2d2; }
- .sdc-tile .sdc-tile-header, .sdc-tile-catalog .sdc-tile-header {
- position: relative;
- flex-shrink: 0;
- display: flex;
- align-items: flex-start;
- flex-direction: column; }
- .sdc-tile .sdc-tile-content, .sdc-tile-catalog .sdc-tile-content {
- position: relative;
- flex: 1;
- display: flex;
- align-items: flex-start;
- flex-direction: column;
- overflow: auto;
- justify-content: space-between; }
- .sdc-tile .sdc-tile-footer, .sdc-tile-catalog .sdc-tile-footer {
- position: relative;
- flex-shrink: 0;
- display: flex;
- align-items: flex-start;
- flex-direction: column; }
-
-.sdc-tile-catalog {
- width: 204px;
- height: 200px; }
- .sdc-tile-catalog .sdc-tile-header {
- line-height: 16px; }
- .sdc-tile-catalog .sdc-tile-header .sdc-tile-header-type {
- font-size: 14px;
- text-transform: uppercase; }
- .sdc-tile-catalog .sdc-tile-header .sdc-tile-header-type.purple {
- color: #9063cd; }
- .sdc-tile-catalog .sdc-tile-header .sdc-tile-header-type.blue {
- color: #009fdb; }
- .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-icon {
- align-items: center;
- display: flex;
- flex-direction: column;
- width: 100%;
- padding-top: 25px; }
- .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-icon svg {
- width: 60px;
- height: 40px; }
- .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-info {
- padding-bottom: 4px;
- width: 180px;
- overflow: hidden;
- text-overflow: ellipsis;
- width: auto;
- white-space: nowrap;
- display: inline-block;
- max-width: 178px; }
- .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-info .sdc-tile-content-info-vendor-name {
- color: #959595;
- line-height: 12px; }
- .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-info .sdc-tile-content-info-item-name {
- color: #191919; }
- .sdc-tile-catalog .sdc-tile-content .sdc-tile-content-info .sdc-tile-content-info-version-info {
- display: flex;
- justify-content: space-between; }
- .sdc-tile-catalog .sdc-tile-footer {
- display: flex;
- flex-direction: row;
- border-top: 1px solid #eaeaea;
- padding: 0;
- width: 180px;
- height: 20px; }
- .sdc-tile-catalog .sdc-tile-footer .sdc-tile-footer-text {
- flex: 1;
- padding-top: 5px;
- overflow: hidden;
- text-overflow: ellipsis;
- width: auto;
- white-space: nowrap;
- display: inline-block;
- max-width: 164px; }
- .sdc-tile-catalog .sdc-tile-footer .sdc-tile-footer-icon {
- flex-shrink: 1;
- overflow: hidden;
- padding-top: 5px; }
- .sdc-tile-catalog .sdc-tile-footer .sdc-tile-footer-icon svg {
- width: 16px;
- height: 20px; }
diff --git a/catalog-ui/src/index.html b/catalog-ui/src/index.html
index 3a66d4da45..044eb374a6 100644
--- a/catalog-ui/src/index.html
+++ b/catalog-ui/src/index.html
@@ -19,7 +19,7 @@
<script src="/sdc1/scripts/inline.bundle.js"></script>
<script src="/sdc1/scripts/polyfills.bundle.js"></script>
<script src="/sdc1/scripts/vendor.bundle.js"></script>
-<script src="/dcae/dcae-bundle.js" async></script>
+<script src="/dcae/dcae-bundle.js"></script>
<script id="main-bundle" src="/sdc1/scripts/main.bundle.js"></script>
<script src="/sdc1/scripts/styles.bundle.js"></script>
diff --git a/catalog-ui/src/third-party/PunchOutRegistry.js b/catalog-ui/src/third-party/PunchOutRegistry.js
index db8e6875d6..506a785c79 100644
--- a/catalog-ui/src/third-party/PunchOutRegistry.js
+++ b/catalog-ui/src/third-party/PunchOutRegistry.js
@@ -18,7 +18,9 @@
* ============LICENSE_END=========================================================
*/
-(function(window) {
+
+
+(function (window) {
"use strict";
if (window.PunchOutRegistry) {
@@ -29,9 +31,20 @@
var factoryPromises = new Map();
var instancePromises = new Map();
+ function loadOnBoarding(callback) {
+
+ if (factoryPromises.has("onboarding/vendor") && !queuedFactoryRequests.has("onboarding/vendor")) {
+ callback();
+ }
+ else {
+ console.log("Load OnBoarding");
+ $.getScript("/onboarding/punch-outs_en.js").then(callback);
+ }
+ }
+
function registerFactory(name, factory) {
if (factoryPromises.has(name) && !queuedFactoryRequests.has(name)) {
- console.error("PunchOut \"" + name + "\" has been already registered");
+ // console.error("PunchOut \"" + name + "\" has been already registered");
return;
}
if (queuedFactoryRequests.has(name)) {
@@ -58,7 +71,7 @@
var factoryPromise;
var instancePromise = instancePromises.get(element);
if (!instancePromise) {
- instancePromise = getFactoryPromise(name).then(function(factory) {
+ instancePromise = getFactoryPromise(name).then(function (factory) {
return factory();
});
instancePromises.set(element, instancePromise);
@@ -69,7 +82,8 @@
function renderPunchOut(params, element) {
var name = params.name;
var options = params.options || {};
- var onEvent = params.onEvent || function () {};
+ var onEvent = params.onEvent || function () {
+ };
getInstancePromise(name, element).then(function (punchOut) {
punchOut.render({options: options, onEvent: onEvent}, element);
@@ -81,7 +95,7 @@
console.error("There is no PunchOut in element", element);
return;
}
- instancePromises.get(element).then(function(punchOut) {
+ instancePromises.get(element).then(function (punchOut) {
punchOut.unmount(element);
});
instancePromises.delete(element);
@@ -90,7 +104,8 @@
var PunchOutRegistry = Object.freeze({
register: registerFactory,
render: renderPunchOut,
- unmount: unmountPunchOut
+ unmount: unmountPunchOut,
+ loadOnBoarding: loadOnBoarding
});
window.PunchOutRegistry = PunchOutRegistry;
diff --git a/catalog-ui/src/third-party/cytoscape.js-edge-editation/CytoscapeEdgeEditation.js b/catalog-ui/src/third-party/cytoscape.js-edge-editation/CytoscapeEdgeEditation.js
index 5731019ff0..0e6ca8b3c2 100644
--- a/catalog-ui/src/third-party/cytoscape.js-edge-editation/CytoscapeEdgeEditation.js
+++ b/catalog-ui/src/third-party/cytoscape.js-edge-editation/CytoscapeEdgeEditation.js
@@ -459,7 +459,8 @@
var handle = handles[i];
var position = this._getHandlePosition(handle, this._hover);
- if (VectorMath.distance(position, mousePoisition) < this.HANDLE_SIZE) {
+ var renderedHandleSize = this.HANDLE_SIZE * this._cy.zoom(); //actual number of pixels that handle uses.
+ if (VectorMath.distance(position, mousePoisition) < renderedHandleSize) {
return {
handle: handle,
position: position
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java
index 30d70cd019..367b806104 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java
@@ -21,6 +21,7 @@
package org.openecomp.sdc.common.util;
import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
public class JsonUtils {
@@ -42,4 +43,16 @@ public class JsonUtils {
}
+ public static boolean containsEntry(JsonObject json, String key) {
+ return json.get(key) != null;
+ }
+
+ public static boolean isEmptyJson(JsonObject json) {
+ return json.entrySet().isEmpty();
+ }
+
+ public static boolean isEmptyJson(JsonElement json) {
+ return json.isJsonPrimitive() ? false : JsonUtils.isEmptyJson(json.getAsJsonObject());
+ }
+
}
diff --git a/openecomp-ui/external-resources/healthcheck/v1.0/healthcheck b/openecomp-ui/external-resources/healthcheck/healthcheck
index 6a3dd41755..e17838f246 100644
--- a/openecomp-ui/external-resources/healthcheck/v1.0/healthcheck
+++ b/openecomp-ui/external-resources/healthcheck/healthcheck
@@ -1,10 +1,10 @@
{
- "sdcVersion": "1.0-SNAPSHOT",
+ "sdcVersion": "{VERSION}",
"componentsInfo": [
{
"healthCheckComponent": "FE",
"healthCheckStatus": "UP",
- "version": "1.0-SNAPSHOT",
+ "version": "{VERSION}",
"description": "OK"
}
]
diff --git a/openecomp-ui/gulpfile.js b/openecomp-ui/gulpfile.js
index eb755a2be0..6d45a0b374 100644
--- a/openecomp-ui/gulpfile.js
+++ b/openecomp-ui/gulpfile.js
@@ -33,14 +33,16 @@ const path = {
svgSrc: './resources/images/svg/*.svg',
appinf: './webapp-onboarding/**/*.*',
jetty: './webapp-onboarding/WEB-INF/jetty-web.xml',
+ healthCheckInput: './external-resources/healthcheck/healthcheck',
srcDir: './src/',
// output
output: dist,
css: dist + '/css',
svg: dist + '/resources/images/svg',
appinf_output: dist + '/webapp-onboarding',
+ healthCheckOutput: dist + '/v1.0',
// war
- war: [dist + '/index.html', dist + '/punch-outs*.js', dist + '/**/*.{css,png,svg,eot,ttf,woff,woff2,otf}', dist + '/**/*(config.json)', dist + '/webapp-onboarding/**'],
+ war: [dist + '/index.html', dist + '/punch-outs*.js', dist + '/**/*.{css,png,svg,eot,ttf,woff,woff2,otf}', dist + '/**/*(config.json)', dist + '/webapp-onboarding/**', dist + '/**/*(healthcheck)'],
heatWar: [dist + '/heat.html', dist + '/heat-validation_en.js', dist + '/**/*.{css,png,svg,eot,ttf,woff,woff2,otf}', dist + '/**/*(config.json)', 'webapp-heat-validation/**'],
wardest: dist,
// storybook
@@ -69,6 +71,17 @@ taskMaker.defineTask('watch', {taskName: 'watch-stuff', src: [path.json, path.in
//TODO: delete this task after gulp-css-usage support for SCSS files
taskMaker.defineTask('sass', {taskName: 'sass', src: path.scss, dest: path.css, config: {outputStyle: 'compressed'}});
+// copy the healthcheck file and replace the version with command line argument
+gulp.task('healthcheck', function(){
+ let args = process.argv;
+ let versionArg = args.find(arg => arg.startsWith('--version'));
+ let version = versionArg && versionArg.slice(versionArg.indexOf('=') + 1);
+ if (versionArg) {
+ gulp.src(path.healthCheckInput)
+ .pipe(replace('{VERSION}', version))
+ .pipe(gulp.dest(path.healthCheckOutput));
+ }
+});
// update the app-context for the web-xml file to the value from the config
gulp.task('app-context', function(){
@@ -86,7 +99,7 @@ gulp.task('copy-stuff', callback => runSequence(['copy-json', 'copy-index.html',
// minimum build for dev
gulp.task('dev', callback => runSequence('clean', 'copy-stuff', callback));
// build procedure for war file
-gulp.task('build', callback => runSequence('clean', 'copy-stuff', 'prod', ['compress-war', 'compress-heat-war'], callback));
+gulp.task('build', callback => runSequence('clean', 'copy-stuff', 'healthcheck', 'prod', ['compress-war', 'compress-heat-war'], callback));
// default build is set to 'dev'
gulp.task('default', ['dev']);
// creating the webpack tasks for the production build
diff --git a/openecomp-ui/pom.xml b/openecomp-ui/pom.xml
index 77313092c6..0e98b7c9c3 100644
--- a/openecomp-ui/pom.xml
+++ b/openecomp-ui/pom.xml
@@ -56,11 +56,11 @@
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.4</version>
-
+
<configuration>
<installDirectory>${project.parent.parent.basedir}</installDirectory>
- </configuration>
-
+ </configuration>
+
<executions>
<execution>
@@ -73,7 +73,7 @@
<npmVersion>3.10.10</npmVersion>
</configuration>
</execution>
-
+
<execution>
<id>npm set progress off</id>
<goals>
@@ -83,7 +83,7 @@
<arguments>set progress=false</arguments>
</configuration>
</execution>
-
+
<execution>
<id>npm install in dox-sequence-diagram-ui</id>
<goals>
@@ -94,7 +94,7 @@
<arguments>install</arguments>
</configuration>
</execution>
-
+
<execution>
<id>npm install</id>
<goals>
@@ -104,14 +104,14 @@
<arguments>install</arguments>
</configuration>
</execution>
-
+
<execution>
<id>npm run build</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
- <arguments>run build</arguments>
+ <arguments>run build -- --version=${version}</arguments>
</configuration>
</execution>
</executions>
diff --git a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default/keystore b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default/keystore
new file mode 100644
index 0000000000..08f6cda8a7
--- /dev/null
+++ b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/files/default/keystore
Binary files differ
diff --git a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_1_cleanup_jettydir.rb b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_1_cleanup_jettydir.rb
index 35147a30fb..d989eb20bb 100644
--- a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_1_cleanup_jettydir.rb
+++ b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_1_cleanup_jettydir.rb
@@ -46,4 +46,3 @@ directory "BE_create_catalog-be" do
mode '0755'
action :create
end
-
diff --git a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_setup_configuration.rb b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_2_setup_configuration.rb
index c8b8615140..ac1614a253 100644
--- a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_setup_configuration.rb
+++ b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_2_setup_configuration.rb
@@ -1,7 +1,8 @@
+jetty_base="/var/lib/jetty"
replication_factor=1
template "titan.properties" do
- path "/var/lib/jetty/config/catalog-be/titan.properties"
+ path "/#{jetty_base}/config/catalog-be/titan.properties"
source "BE-titan.properties.erb"
owner "jetty"
group "jetty"
@@ -17,7 +18,7 @@ end
template "catalog-be-config" do
- path "/var/lib/jetty/config/catalog-be/configuration.yaml"
+ path "/#{jetty_base}/config/catalog-be/configuration.yaml"
source "BE-configuration.yaml.erb"
owner "jetty"
group "jetty"
@@ -35,7 +36,7 @@ end
template "distribution-engine-configuration" do
- path "/var/lib/jetty/config/catalog-be/distribution-engine-configuration.yaml"
+ path "/#{jetty_base}/config/catalog-be/distribution-engine-configuration.yaml"
source "BE-distribution-engine-configuration.yaml.erb"
owner "jetty"
group "jetty"
@@ -44,11 +45,24 @@ end
cookbook_file "ArtifactGenerator" do
- path "/var/lib/jetty/config/catalog-be/Artifact-Generator.properties"
+ path "/#{jetty_base}/config/catalog-be/Artifact-Generator.properties"
source "Artifact-Generator.properties"
owner "jetty"
group "jetty"
mode "0755"
end
-
+directory "Jetty_etcdir_creation" do
+ path "/#{jetty_base}/etc"
+ owner 'jetty'
+ group 'jetty'
+ mode '0755'
+ action :create
+end
+
+cookbook_file "/#{jetty_base}/etc/keystore" do
+ source "keystore"
+ owner "jetty"
+ group "jetty"
+ mode 0755
+end
diff --git a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_2_locate_wars.rb b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_jetty_Modules.rb
index af3dea15ef..3ec16e8924 100644
--- a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_2_locate_wars.rb
+++ b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_jetty_Modules.rb
@@ -12,15 +12,4 @@ EOH
not_if "ls /#{jetty_base}/start.d/https.ini"
end
-###### copy catalog-be.war
-
-
-
-###### copy onboarding-be.war& api-docs.war
-#bash "copy-onboarding-be" do
-# code <<-EOH
-# /bin/tar -xvf /var/tmp/onboarding-be.tar -C /var/tmp/
-# mv /var/tmp/onboarding-be*.war /var/tmp//api-docs*.war #{jetty_base}/webapps
-# EOH
-#end
diff --git a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb
index cbecfdbbe9..df9e74ad51 100644
--- a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb
+++ b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb
@@ -141,6 +141,7 @@ resourceTypes: &allResourceTypes
- VF
- VFCMT
- Abstract
+ - CVFC
# validForResourceTypes usage
# validForResourceTypes:
@@ -177,6 +178,8 @@ toscaArtifacts:
#Informational artifacts placeHolder
excludeResourceCategory:
- Generic
+excludeResourceType:
+ - PNF
informationalResourceArtifacts:
features:
displayName: Features
@@ -285,10 +288,12 @@ serviceDeploymentArtifacts:
MODEL_QUERY_SPEC:
acceptedTypes:
- xml
- AAI_SERVICE_MODEL:
+ UCPE_LAYER_2_CONFIGURATION:
acceptedTypes:
- xml
- UCPE_LAYER_2_CONFIGURATION:
+
+#AAI Artifacts
+ AAI_SERVICE_MODEL:
acceptedTypes:
- xml
AAI_VF_MODULE_MODEL:
@@ -296,11 +301,10 @@ serviceDeploymentArtifacts:
- xml
AAI_VF_INSTANCE_MODEL:
acceptedTypes:
- - xml
+ - xml
OTHER:
acceptedTypes:
-
resourceDeploymentArtifacts:
HEAT:
acceptedTypes:
@@ -369,7 +373,6 @@ resourceDeploymentArtifacts:
acceptedTypes:
validForResourceTypes:
- VF
- #DCAE Artifacts
DCAE_TOSCA:
acceptedTypes:
- yml
@@ -392,14 +395,13 @@ resourceDeploymentArtifacts:
DCAE_DOC:
acceptedTypes:
validForResourceTypes:
- - VF
- - VFCMT
+ - VF
+ - VFCMT
DCAE_EVENT:
acceptedTypes:
validForResourceTypes:
- VF
- VFCMT
-#AAI Artifacts
AAI_VF_MODEL:
acceptedTypes:
- xml
@@ -434,7 +436,6 @@ resourceInstanceDeploymentArtifacts:
PERFORMANCE_COUNTER:
acceptedTypes:
- csv
-#DCAE_VF Instance Artifacts
DCAE_INVENTORY_TOSCA:
acceptedTypes:
- yml
@@ -488,7 +489,15 @@ resourceInformationalArtifacts:
validForResourceTypes: *allResourceTypes
OTHER:
acceptedTypes:
- validForResourceTypes: *allResourceTypes
+ validForResourceTypes:
+ - VFC
+ - CVFC
+ - CP
+ - VL
+ - VF
+ - VFCMT
+ - Abstract
+ - PNF
SNMP_POLL:
acceptedTypes:
validForResourceTypes: *allResourceTypes
@@ -500,6 +509,7 @@ resourceInformationalArtifacts:
validForResourceTypes:
- VF
- VFC
+ - CVFC
resourceInformationalDeployedArtifacts:
@@ -519,10 +529,8 @@ cleanComponentsConfiguration:
artifactsIndex: resources
-heatEnvArtifactHeader:
- ""
-heatEnvArtifactFooter:
- ""
+heatEnvArtifactHeader: ""
+heatEnvArtifactFooter: ""
onboarding:
protocol: http
@@ -589,5 +597,7 @@ vfModuleProperties:
genericAssetNodeTypes:
VFC: org.openecomp.resource.abstract.nodes.VFC
+ CVFC: org.openecomp.resource.abstract.nodes.VFC
VF : org.openecomp.resource.abstract.nodes.VF
+ PNF: org.openecomp.resource.abstract.nodes.PNF
Service: org.openecomp.resource.abstract.nodes.service
diff --git a/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-onboarding-configuration.yaml.erb b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-onboarding-configuration.yaml.erb
new file mode 100644
index 0000000000..4646661dfb
--- /dev/null
+++ b/sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-onboarding-configuration.yaml.erb
@@ -0,0 +1,5 @@
+notifications:
+ pollingIntervalMsec: 2000
+ selectionSize: 100
+ beHost: <%= @catalog_ip %>
+ beHttpPort: <%= @catalog_port %> \ No newline at end of file
diff --git a/sdc-os-chef/sdc-backend/chef-solo/roles/catalog-be.json b/sdc-os-chef/sdc-backend/chef-solo/roles/catalog-be.json
index e8928bbdc7..9fc7b8d1dc 100644
--- a/sdc-os-chef/sdc-backend/chef-solo/roles/catalog-be.json
+++ b/sdc-os-chef/sdc-backend/chef-solo/roles/catalog-be.json
@@ -11,8 +11,8 @@
"chef_type": "role",
"run_list": [
"recipe[sdc-catalog-be::BE_1_cleanup_jettydir]",
- "recipe[sdc-catalog-be::BE_2_locate_wars]",
- "recipe[sdc-catalog-be::BE_4_setup_configuration]",
+ "recipe[sdc-catalog-be::BE_2_setup_configuration]",
+ "recipe[sdc-catalog-be::BE_4_jetty_Modules]",
"recipe[sdc-catalog-be::BE_5_setup_elasticsearch]",
"recipe[sdc-catalog-be::BE_6_setup_portal_properties]",
"recipe[sdc-catalog-be::BE_7_logback]",
diff --git a/sdc-os-chef/sdc-backend/startup.sh b/sdc-os-chef/sdc-backend/startup.sh
index 5d88aa68ec..98699d9486 100644
--- a/sdc-os-chef/sdc-backend/startup.sh
+++ b/sdc-os-chef/sdc-backend/startup.sh
@@ -6,7 +6,7 @@ cd /root/chef-solo
echo "normal['HOST_IP'] = \"${HOST_IP}\"" > /root/chef-solo/cookbooks/sdc-catalog-be/attributes/default.rb
chef-solo -c solo.rb -E ${CHEFNAME}
-sed -i '/^set -e/aJAVA_OPTIONS=\" -XX:MaxPermSize=256m -Xmx1500m -Dconfig.home=${JETTY_BASE}\/config -Dlog.home=${JETTY_BASE}\/logs -Dlogback.configurationFile=${JETTY_BASE}\/config\/catalog-be\/logback.xml -Dconfiguration.yaml=${JETTY_BASE}\/config\/catalog-be\/configuration.yaml -Dartifactgenerator.config=${JETTY_BASE}\/config\/catalog-be\/Artifact-Generator.properties\" ' /docker-entrypoint.sh
+sed -i '/^set -e/aJAVA_OPTIONS=\" -XX:MaxPermSize=256m -Xmx1500m -Dconfig.home=${JETTY_BASE}\/config -Dlog.home=${JETTY_BASE}\/logs -Dlogback.configurationFile=${JETTY_BASE}\/config\/catalog-be\/logback.xml -Dconfiguration.yaml=${JETTY_BASE}\/config\/catalog-be\/configuration.yaml -Dartifactgenerator.config=${JETTY_BASE}\/config\/catalog-be\/Artifact-Generator.properties\ -Donboarding_configuration.yaml=${JETTY_BASE}\/config\/onboarding-be\/onboarding_configuration.yaml" ' /docker-entrypoint.sh
sed -i '/^set -e/aTMPDIR=${JETTY_BASE}\/temp' /docker-entrypoint.sh
# executiong the jetty
diff --git a/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/files/default/keystore b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/files/default/keystore
new file mode 100644
index 0000000000..08f6cda8a7
--- /dev/null
+++ b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/files/default/keystore
Binary files differ
diff --git a/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_1_cleanup_jettydir.rb b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_1_cleanup_jettydir.rb
index 29301a9418..25983700d2 100644
--- a/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_1_cleanup_jettydir.rb
+++ b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_1_cleanup_jettydir.rb
@@ -47,3 +47,11 @@ directory "FE_create_catalog-fe" do
action :create
end
+
+directory "FE_create_catalog-fe" do
+ path "/var/lib/jetty/config/onboarding-fe"
+ owner 'jetty'
+ group 'jetty'
+ mode '0755'
+ action :create
+end \ No newline at end of file
diff --git a/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_2_setup_configuration.rb b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_2_setup_configuration.rb
index 64d71768cd..0ad5c0f356 100644
--- a/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_2_setup_configuration.rb
+++ b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_2_setup_configuration.rb
@@ -1,5 +1,6 @@
+jetty_base="/var/lib/jetty"
template "catalog-fe-config" do
- path "/var/lib/jetty/config/catalog-fe/configuration.yaml"
+ path "#{jetty_base}/config/catalog-fe/configuration.yaml"
source "FE-configuration.yaml.erb"
owner "jetty"
group "jetty"
@@ -11,3 +12,17 @@ template "catalog-fe-config" do
:ssl_port => node['BE'][:https_port]
})
end
+
+
+template "onboarding-fe-config" do
+ path "#{jetty_base}/config/onboarding-fe/onboarding_configuration.yaml"
+ source "FE-onboarding-configuration.yaml.erb"
+ owner "jetty"
+ group "jetty"
+ mode "0755"
+ variables({
+ :catalog_ip => node['HOST_IP'],
+ :catalog_port => node['BE'][:http_port],
+ :ssl_port => node['BE'][:https_port]
+})
+end \ No newline at end of file
diff --git a/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_7_locate_keystore.rb b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_7_locate_keystore.rb
new file mode 100644
index 0000000000..bdf0d37b28
--- /dev/null
+++ b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_7_locate_keystore.rb
@@ -0,0 +1,16 @@
+jetty_base="/var/lib/jetty"
+
+directory "Jetty_etcdir_creation" do
+ path "/#{jetty_base}/etc"
+ owner 'jetty'
+ group 'jetty'
+ mode '0755'
+ action :create
+end
+
+cookbook_file "/#{jetty_base}/etc/keystore" do
+ source "keystore"
+ owner "jetty"
+ group "jetty"
+ mode 0755
+end
diff --git a/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-configuration.yaml.erb b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-configuration.yaml.erb
index 6a6ea29608..b730c509c7 100644
--- a/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-configuration.yaml.erb
+++ b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-configuration.yaml.erb
@@ -60,7 +60,6 @@ optionalHeaderFields:
- &HTTP_CSP_EMAIL HTTP_CSP_EMAIL
- &csp-email csp-email
-
version: 1.0
released: 2012-11-30
diff --git a/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-onboarding-configuration.yaml.erb b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-onboarding-configuration.yaml.erb
new file mode 100644
index 0000000000..4646661dfb
--- /dev/null
+++ b/sdc-os-chef/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/FE-onboarding-configuration.yaml.erb
@@ -0,0 +1,5 @@
+notifications:
+ pollingIntervalMsec: 2000
+ selectionSize: 100
+ beHost: <%= @catalog_ip %>
+ beHttpPort: <%= @catalog_port %> \ No newline at end of file
diff --git a/sdc-os-chef/sdc-frontend/chef-solo/roles/catalog-fe.json b/sdc-os-chef/sdc-frontend/chef-solo/roles/catalog-fe.json
index 9e023762d1..547c00657c 100644
--- a/sdc-os-chef/sdc-frontend/chef-solo/roles/catalog-fe.json
+++ b/sdc-os-chef/sdc-frontend/chef-solo/roles/catalog-fe.json
@@ -15,7 +15,8 @@
"recipe[sdc-catalog-fe::FE_3_errors_config]",
"recipe[sdc-catalog-fe::FE_4_logback]",
"recipe[sdc-catalog-fe::FE_5_rest_configuration]",
- "recipe[sdc-catalog-fe::FE_6_create_jetty_modules]"
+ "recipe[sdc-catalog-fe::FE_7_locate_keystore]",
+ "recipe[sdc-catalog-fe::FE_6_create_jetty_modules]"
],
"env_run_lists": {
}
diff --git a/sdc-os-chef/sdc-frontend/startup.sh b/sdc-os-chef/sdc-frontend/startup.sh
index ee6e7f528a..82f01576ef 100644
--- a/sdc-os-chef/sdc-frontend/startup.sh
+++ b/sdc-os-chef/sdc-frontend/startup.sh
@@ -5,7 +5,7 @@ cd /root/chef-solo
echo "normal['HOST_IP'] = \"${HOST_IP}\"" > /root/chef-solo/cookbooks/sdc-catalog-fe/attributes/default.rb
chef-solo -c solo.rb -E ${CHEFNAME}
-sed -i '/^set -e/aJAVA_OPTIONS=\"-XX:MaxPermSize=256m -Xmx1500m -Dconfig.home=${JETTY_BASE}\/config -Dlog.home=${JETTY_BASE}\/logs -Dlogback.configurationFile=${JETTY_BASE}\/config\/catalog-fe\/logback.xml -Dconfiguration.yaml=${JETTY_BASE}\/config\/catalog-fe\/configuration.yaml\"' /docker-entrypoint.sh
+sed -i '/^set -e/aJAVA_OPTIONS=\"-XX:MaxPermSize=256m -Xmx1500m -Dconfig.home=${JETTY_BASE}\/config -Dlog.home=${JETTY_BASE}\/logs -Dlogback.configurationFile=${JETTY_BASE}\/config\/catalog-fe\/logback.xml -Dconfiguration.yaml=${JETTY_BASE}\/config\/catalog-fe\/configuration.yaml -Donboarding_configuration.yaml=${JETTY_BASE}\/config\/onboarding-fe\/onboarding_configuration.yaml\"' /docker-entrypoint.sh
sed -i '/^set -e/aTMPDIR=${JETTY_BASE}\/temp' /docker-entrypoint.sh
cd /var/lib/jetty
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/AndreyTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/AndreyTest.java
index 45c6b18b59..a2683eafc8 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/AndreyTest.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/AndreyTest.java
@@ -25,15 +25,18 @@ import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
+import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Map;
-import org.openecomp.sdc.ci.tests.datatypes.GroupHeatMetaDefinition;
-import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition;
-import org.openecomp.sdc.ci.tests.datatypes.TypeHeatMetaDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition;
-import org.openecomp.sdc.ci.tests.utils.CsarParserUtils;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaTopologyTemplateDefinition;
import org.openecomp.sdc.ci.tests.utils.ToscaParserUtils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
import org.openecomp.sdc.tosca.parser.api.ISdcCsarHelper;
import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException;
import org.openecomp.sdc.tosca.parser.impl.SdcToscaParserFactory;
@@ -49,13 +52,32 @@ public class AndreyTest {
public static void main(String[] args) throws Exception {
- ToscaDefinition toscaDefinition;
+ ToscaDefinition toscaMainAmdocsDefinition, toscaMainVfDefinition, toscaMainServiceDefinition;
+ File filesFolder = new File("C:/Users/al714h/Downloads/Design/");
+ File amdocsCsarFileName = new File("/77e6b842669f441db20a83489da3f4be.csar");
+ File VfCsarFileName = new File("/resource-Civfonboarded2016012VmxAv301072E2e1424cb9d-csar.csar");
+ File serviceCsarFileName = new File("/service-Ciservicefeba0521131d-csar.csar");
+
System.out.println("start " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
+
// File path = new File("C:/Data/D2.0/TOSCA_Ex/Definitions/tosca_definition_version.yaml");
// File path = new File("C:/Data/D2.0/TOSCA_Ex/resource-Vl11Vl10-template.yml");
// File path = new File("C:/Data/D2.0/TOSCA_Ex/service-Servicepxtc-template US822998.yml");
// File path = new File("C:/Data/FileToParse/Definitions/service-Ciservice513e6fa67d07-template.yml");
- toscaDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File("C:/Data/FileToParse/LDSA/LDSA_amdocs.csar"));
+// toscaMainAmdocsDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File("C:/Data/FileToParse/LDSA/service-LdsaService-csar.csar"));
+ toscaMainAmdocsDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + amdocsCsarFileName));
+ toscaMainVfDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + VfCsarFileName));
+ toscaMainServiceDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + serviceCsarFileName));
+ Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, "Generic_VF", "1.0");
+ ToscaTopologyTemplateDefinition topology_template = toscaMainAmdocsDefinition.getTopology_template();
+ Map<String, Object> newInput = new HashMap<String, Object>();
+ for (PropertyDefinition property : resource.getProperties()) {
+ newInput.put(property.getLabel(),property);
+ }
+ topology_template.setInputs(newInput);
+
+
+ List<PropertyDefinition> properties = resource.getProperties();
// File path = new File("C:/Data/FileToParse/Definitions/resource-Civfonboarded2016006VvmVvm301607E2100a9b04-template.yml");
// File csarPath = new File("C:/Data/D2.0/TOSCA_Ex/Nested.csar");
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java
index e387cd2544..70ed1d51f0 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java
@@ -84,8 +84,7 @@ public class CatalogRestUtils extends BaseRestUtils {
public static RestResponse getOsVersion() throws IOException {
Config config = Utils.getConfig();
- String url = String.format(Urls.OS_VERSION, config.getCatalogBeHost(),
- config.getCatalogBePort());
+ String url = String.format(Urls.OS_VERSION, config.getCatalogBeHost(), config.getCatalogBePort());
return sendGet(url, UserRoleEnum.DESIGNER.getUserId());
}
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java
index f4d9fe3f35..1bef06ac03 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java
@@ -92,8 +92,13 @@ public class AuditValidationUtils {
}
public static String buildAuditDescription(ErrorInfo errorInfo, List<String> errorVariablesList) {
-
- String auditDesc = errorInfo.getMessageId() + ": " + errorInfo.getMessage();
+ String auditDesc;
+ if(errorInfo.getMessageId() != null){
+ auditDesc = errorInfo.getMessageId() + ": " + errorInfo.getMessage();
+ }else{
+ auditDesc = errorInfo.getMessage();
+ }
+
// if(! variables.isEmpty() && variables.get(0) != null && ! variables.get(0).isEmpty()){
// for (int i = 0; i < variables.size(); i++) {
// if (auditDesc.contains("%" + (i + 1))) {
@@ -101,7 +106,7 @@ public class AuditValidationUtils {
// }
// }
// }
- if(! errorVariablesList.isEmpty() && errorVariablesList.get(0) != null){
+ if(errorVariablesList != null && ! errorVariablesList.isEmpty() && errorVariablesList.get(0) != null){
for (int i = 0; i < errorVariablesList.size(); i++) {
if (auditDesc.contains("%" + (i + 1))) {
auditDesc = auditDesc.replace("%" + (i + 1), errorVariablesList.get(i));
@@ -659,8 +664,7 @@ public class AuditValidationUtils {
public static void compareElements(Object expectedValue, Object foundValue) {
if (expectedValue instanceof String) {
assertTrue("Actual value " + foundValue + " is not string", foundValue instanceof String);
- assertTrue("Expected " + expectedValue + " not equal to actual " + foundValue,
- foundValue.equals(expectedValue));
+ assertTrue("Expected " + "[" + expectedValue +"]" + " not equal to actual [" + foundValue + "]", foundValue.equals(expectedValue));
}
/*
* else if( expectedValue instanceof Number){ assertTrue(foundValue
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java
index 127ae54784..61b7ea18d2 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java
@@ -81,6 +81,7 @@ import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
import org.openecomp.sdc.ci.tests.utils.validation.DistributionValidationUtils;
import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
@@ -89,6 +90,7 @@ import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.openecomp.sdc.common.util.GeneralUtility;
+import org.openecomp.sdc.common.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
@@ -131,95 +133,95 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="uploadArtifactOnVfcVlCpViaExternalAPI" , parallel=true)
public static Object[][] dataProviderUploadArtifactOnVfcVlCpViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.CP},
-
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.CP},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.CP}
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP}
};
}
@@ -234,47 +236,47 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="uploadArtifactOnVFViaExternalAPI", parallel=true)
public static Object[][] dataProviderUploadArtifactOnVFViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_JSON"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_POLICY"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_EVENT"},
- {LifeCycleStatesEnum.CHECKOUT, "APPC_CONFIG"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_DOC"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_TOSCA"},
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE"},
- {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE"},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER"},
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_JSON"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_POLICY"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_EVENT"},
- {LifeCycleStatesEnum.CHECKIN, "APPC_CONFIG"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_DOC"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_TOSCA"},
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML"},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE"},
- {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE"},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CHECKIN, "OTHER"},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_JSON"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_POLICY"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_EVENT"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "APPC_CONFIG"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_DOC"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_TOSCA"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER"}
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_JSON.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_POLICY.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_EVENT.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.APPC_CONFIG.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_DOC.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_TOSCA.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VF_LICENSE.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VENDOR_LICENSE.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_JSON.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_POLICY.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_EVENT.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.APPC_CONFIG.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_DOC.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_TOSCA.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VF_LICENSE.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VENDOR_LICENSE.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_JSON.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_POLICY.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_EVENT.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.APPC_CONFIG.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_DOC.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_TOSCA.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VF_LICENSE.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VENDOR_LICENSE.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType()}
};
}
@@ -290,21 +292,21 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="uploadArtifactOnServiceViaExternalAPI" , parallel=true)
public static Object[][] dataProviderUploadArtifactOnServiceViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML"},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER"}
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType()}
};
}
@@ -319,7 +321,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="uploadArtifactOnServiceViaExternalAPIIncludingDistribution", parallel=true)
public static Object[][] dataProviderUploadArtifactOnServiceViaExternalAPIIncludingDistribution() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType()},
};
}
@@ -590,33 +592,33 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="uploadArtifactOnRIViaExternalAPI", parallel=true)
public static Object[][] dataProviderUploadArtifactOnRIViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT"},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL"},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP"},
-
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT"},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL"},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP"},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP"}
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType()},
+
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType()},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType()}
};
}
@@ -636,88 +638,88 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="uploadArtifactOnVfcVlCpRIViaExternalAPI", parallel=true)
public static Object[][] dataProviderUploadArtifactOnVfcVlCpRIViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
-
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.CP},
-
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.CP},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.CP}
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP},
+
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP}
};
}
@@ -821,13 +823,13 @@ public class CRUDExternalAPI extends ComponentBaseTest {
{LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithSameLabel"},
- {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
+// 322151 {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "uploadArtifactWithSameLabel"},
- {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
+// 322151 {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "uploadArtifactWithSameLabel"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
+// 322151 {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidCheckSum"},
{LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidCheckSum"},
@@ -861,7 +863,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
componentResourceInstanceDetails = resourceDetails.getComponentInstances().get(0);
} else {
artifactReqDetails = ElementFactory.getArtifactByType("Abcd", ArtifactTypeEnum.OTHER.toString(), true, false);
-
resourceDetails = getComponentInTargetLifeCycleState(componentTypeEnum.toString(), UserRoleEnum.DESIGNER, chosenLifeCycleState, null);
}
@@ -909,7 +910,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
List<String> variables = asList(artifactReqDetails.getArtifactType());
uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
+ artifactReqDetails, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with invalid type via external API - empty type
@@ -920,7 +921,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
List<String> variables = asList(artifactReqDetails.getArtifactType());
uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
+ artifactReqDetails, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with invalid checksum via external API
@@ -929,7 +930,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_INVALID_MD5.name());
List<String> variables = asList();
uploadArtifactWithInvalidCheckSumOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables);
+ artifactReqDetails, componentResourceInstanceDetails, errorInfo, variables);
}
@@ -940,7 +941,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
List<String> variables = asList("artifact name", "255");
artifactReqDetails.setArtifactName("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
+ artifactReqDetails, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
@@ -952,7 +953,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
artifactReqDetails.setArtifactName("");
uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
+ artifactReqDetails, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
@@ -964,7 +965,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
List<String> variables = asList("artifact label", "255");
artifactReqDetails.setArtifactLabel("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
+ artifactReqDetails, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
@@ -976,7 +977,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
List<String> variables = asList("artifact label");
artifactReqDetails.setArtifactLabel("");
uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
+ artifactReqDetails, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
@@ -988,7 +989,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
List<String> variables = asList("artifact description", "256");
artifactReqDetails.setDescription("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
+ artifactReqDetails, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
@@ -1000,7 +1001,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
List<String> variables = asList("artifact description");
artifactReqDetails.setDescription("");
uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
+ artifactReqDetails, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
@@ -1022,12 +1023,14 @@ public class CRUDExternalAPI extends ComponentBaseTest {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_EXIST.name());
List<String> variables = asList(artifactDefinition.getArtifactDisplayName());
+ ArtifactReqDetails artifactReqDetailsSameLabel = ElementFactory.getArtifactByType("Abcd", ArtifactTypeEnum.DCAE_INVENTORY_EVENT.toString(), true, false);
+ artifactReqDetailsSameLabel.setArtifactLabel(artifactReqDetails.getArtifactLabel());
uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
+ artifactReqDetailsSameLabel, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
protected RestResponse uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
- Integer expectedResponseCode, ComponentInstance componentResourceInstanceDetails, ErrorInfo errorInfo, List<String> variables, LifeCycleStatesEnum lifeCycleStatesEnum, Boolean includeResourceNameInAudit) throws Exception {
+ ComponentInstance componentResourceInstanceDetails, ErrorInfo errorInfo, List<String> variables, LifeCycleStatesEnum lifeCycleStatesEnum, Boolean includeResourceNameInAudit) throws Exception {
RestResponse restResponse;
if(componentResourceInstanceDetails != null) {
@@ -1039,7 +1042,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// validate response code
Integer responseCode = restResponse.getErrorCode();
- Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct.");
+ Assert.assertEquals(responseCode, errorInfo.getCode(), "Response code is not correct.");
// Check auditing for upload operation
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
@@ -1081,12 +1084,8 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
-
-
-
-
protected RestResponse uploadArtifactWithInvalidCheckSumOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
- Integer expectedResponseCode, ComponentInstance componentResourceInstanceDetails, ErrorInfo errorInfo, List<String> variables) throws Exception {
+ ComponentInstance componentResourceInstanceDetails, ErrorInfo errorInfo, List<String> variables) throws Exception {
RestResponse restResponse;
if(componentResourceInstanceDetails != null) {
@@ -1098,7 +1097,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// validate response code
Integer responseCode = restResponse.getErrorCode();
- Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct.");
+ Assert.assertEquals(responseCode, errorInfo.getCode(), "Response code is not correct.");
// Check auditing for upload operation
// ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS.name());
@@ -1134,12 +1133,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
-
-
-
-
-
-
@DataProvider(name="uploadArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset", parallel=true)
public static Object[][] dataProviderUploadArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset() {
return new Object[][] {
@@ -1212,18 +1205,15 @@ public class CRUDExternalAPI extends ComponentBaseTest {
List<String> variables = asList();
uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(userRoleEnum),
- artifactReqDetails, 409, componentResourceInstanceDetails, errorInfo, variables, lifeCycleStatesEnum, true);
+ artifactReqDetails, componentResourceInstanceDetails, errorInfo, variables, lifeCycleStatesEnum, true);
// if(lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CHECKIN)) {
// performeClean();
// }
}
-
-
-
-
- @DataProvider(name="uploadArtifactOnAssetWhichNotExist", parallel=true)
+
+ @DataProvider(name="uploadArtifactOnAssetWhichNotExist", parallel=false)
public static Object[][] dataProviderUploadArtifactOnAssetWhichNotExist() {
return new Object[][] {
{ComponentTypeEnum.SERVICE},
@@ -1251,7 +1241,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
resourceDetails.setUUID("12345");
componentResourceInstanceDetails.setNormalizedName("12345");
} else {
- artifactReqDetails = ElementFactory.getArtifactByType("Abcd", "OTHER", true, false);
+ artifactReqDetails = ElementFactory.getArtifactByType("Abcd", ArtifactTypeEnum.OTHER.getType(), true, false);
resourceDetails = getComponentInTargetLifeCycleState(componentTypeEnum.toString(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, null);
@@ -1266,7 +1256,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
List<String> variables = asList(resourceDetails.getUUID());
uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 404, componentResourceInstanceDetails, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, false);
+ artifactReqDetails, componentResourceInstanceDetails, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, false);
// performeClean();
@@ -1306,7 +1296,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
resourceDetails.getLastUpdaterFullName().split(" ")[1], resourceDetails.getLastUpdaterUserId());
uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- artifactReqDetails, 403, componentResourceInstanceDetails, errorInfo, variables, LifeCycleStatesEnum.STARTCERTIFICATION, true);
+ artifactReqDetails, componentResourceInstanceDetails, errorInfo, variables, LifeCycleStatesEnum.STARTCERTIFICATION, true);
}
@@ -1321,32 +1311,30 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="updateArtifactForServiceViaExternalAPI", parallel=true)
public static Object[][] dataProviderUpdateArtifactForServiceViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML"},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER"},
- {LifeCycleStatesEnum.CERTIFY, "YANG_XML"},
- {LifeCycleStatesEnum.CERTIFY, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CERTIFY, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CERTIFY, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CERTIFY, "OTHER"}
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType()},
+ {LifeCycleStatesEnum.CERTIFY, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CERTIFY, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CERTIFY, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CERTIFY, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CERTIFY, ArtifactTypeEnum.OTHER.getType()}
};
}
-
-
// Update artifact for Service - Success
@Test(dataProvider="updateArtifactForServiceViaExternalAPI")
public void updateArtifactForServiceViaExternalAPI(LifeCycleStatesEnum lifeCycleStatesEnum, String artifactType) throws Exception {
@@ -1364,47 +1352,47 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="updateArtifactForVFViaExternalAPI", parallel=true)
public static Object[][] dataProviderUpdateArtifactForVFViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_JSON"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_POLICY"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_EVENT"},
- {LifeCycleStatesEnum.CHECKOUT, "APPC_CONFIG"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_DOC"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_TOSCA"},
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE"},
- {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE"},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER"},
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_JSON"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_POLICY"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_EVENT"},
- {LifeCycleStatesEnum.CHECKIN, "APPC_CONFIG"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_DOC"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_TOSCA"},
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML"},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE"},
- {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE"},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CHECKIN, "OTHER"},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_JSON"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_POLICY"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_EVENT"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "APPC_CONFIG"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_DOC"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_TOSCA"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER"}
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_JSON.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_POLICY.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_EVENT.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.APPC_CONFIG.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_DOC.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_TOSCA.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VF_LICENSE.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VENDOR_LICENSE.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_JSON.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_POLICY.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_EVENT.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.APPC_CONFIG.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_DOC.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_TOSCA.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VF_LICENSE.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VENDOR_LICENSE.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_JSON.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_POLICY.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_EVENT.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.APPC_CONFIG.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_DOC.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_TOSCA.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VF_LICENSE.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VENDOR_LICENSE.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType()}
};
}
@@ -1426,95 +1414,95 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="updateArtifactForVfcVlCpViaExternalAPI", parallel=true)
public static Object[][] dataProviderUpdateArtifactForVfcVlCpViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.CP},
-
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.CP},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.CP}
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP}
};
}
@@ -1545,17 +1533,21 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// Verify that it cannot update VFC/VL/CP artifact on VFCi/VLi/CPi - Failure flow
@Test(dataProvider="updateArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI")
public void updateArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI(ResourceTypeEnum resourceTypeEnum) throws Exception {
+
+ if(true){
+ throw new SkipException("Open bug 321612");
+ }
getExtendTest().log(Status.INFO, String.format("resourceTypeEnum: %s", resourceTypeEnum));
Component resourceInstanceDetails = getComponentInTargetLifeCycleState(ComponentTypeEnum.RESOURCE.getValue(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, resourceTypeEnum);
- ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", "SNMP_TRAP", true, false);
+ ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", ArtifactTypeEnum.SNMP_TRAP.getType(), true, false);
uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceInstanceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, 200);
resourceInstanceDetails = AtomicOperationUtils.changeComponentState(resourceInstanceDetails, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
Component component = getComponentInTargetLifeCycleState(ComponentTypeEnum.RESOURCE.toString(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, null);
AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceInstanceDetails, component, UserRoleEnum.DESIGNER, true).left().value();
component = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, component.getName(), component.getVersion());
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name());
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
Map<String, ArtifactDefinition> deploymentArtifacts;
deploymentArtifacts = getDeploymentArtifactsOfAsset(component, ComponentTypeEnum.RESOURCE_INSTANCE);
String artifactUUID = null;
@@ -1566,33 +1558,33 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
}
List<String> variables = asList(artifactUUID);
- updateArtifactOnAssetViaExternalAPI(component, ComponentTypeEnum.RESOURCE_INSTANCE, LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", errorInfo, variables, UserRoleEnum.DESIGNER, 404);
+ updateArtifactOnAssetViaExternalAPI(component, ComponentTypeEnum.RESOURCE_INSTANCE, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), errorInfo, variables, UserRoleEnum.DESIGNER);
}
@DataProvider(name="updateArtifactOnRIViaExternalAPI", parallel=true)
public static Object[][] dataProviderUpdateArtifactOnRIViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", null},
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", null},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VF},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VF},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VF},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VF},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VF},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VF}
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), null},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), null},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), null},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), null},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), null},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), null},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), null},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), null},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), null},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), null},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), null},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), null},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VF},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VF},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VF},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VF},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VF},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VF}
};
}
@@ -1613,88 +1605,88 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="updateArtifactOnVfcVlCpRIViaExternalAPI", parallel=true)
public static Object[][] dataProviderUpdateArtifactOnVfcVlCpRIViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
-
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.CP},
-
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.CP},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.CP}
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP},
+
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP}
};
}
@@ -1716,48 +1708,48 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset", parallel=true)
public static Object[][] dataProviderUpdateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset() {
return new Object[][] {
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
-
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
-
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"},
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
-
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"},
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
-
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"},
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
-
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"},
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
-
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"},
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
};
}
@@ -1765,20 +1757,23 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// Update artifact by diffrent user then creator of asset - Fail
@Test(dataProvider="updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset")
public void updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset(ComponentTypeEnum componentTypeEnum, UserRoleEnum userRoleEnum, LifeCycleStatesEnum lifeCycleStatesEnum, String artifactType) throws Exception {
+ if(true){
+ throw new SkipException("Open bug 321612");
+ }
getExtendTest().log(Status.INFO, String.format("componentTypeEnum: %s, userRoleEnum: %s, lifeCycleStatesEnum: %s, artifactType: %s", componentTypeEnum, userRoleEnum, lifeCycleStatesEnum, artifactType));
Component component = uploadArtifactOnAssetViaExternalAPI(componentTypeEnum, LifeCycleStatesEnum.CHECKIN, artifactType, null);
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
List<String> variables = asList();
- updateArtifactOnAssetViaExternalAPI(component, componentTypeEnum, lifeCycleStatesEnum, artifactType, errorInfo, variables, userRoleEnum, 409);
+ updateArtifactOnAssetViaExternalAPI(component, componentTypeEnum, lifeCycleStatesEnum, artifactType, errorInfo, variables, userRoleEnum);
}
@DataProvider(name="updateArtifactOnAssetWhichNotExist", parallel=true)
public static Object[][] dataProviderUpdateArtifactOnAssetWhichNotExist() {
return new Object[][] {
- {ComponentTypeEnum.SERVICE, "OTHER", null},
- {ComponentTypeEnum.RESOURCE, "OTHER", null},
- {ComponentTypeEnum.RESOURCE_INSTANCE, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VF},
+ {ComponentTypeEnum.SERVICE, ArtifactTypeEnum.OTHER.getType(), null},
+ {ComponentTypeEnum.RESOURCE, ArtifactTypeEnum.OTHER.getType(), null},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VF},
};
}
@@ -1801,10 +1796,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, component.getComponentInstances().get(0), artifactReqDetails, invalidArtifactUUID, errorInfo, variables, null, true);
+ component.getComponentInstances().get(0), artifactReqDetails, invalidArtifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, null, artifactReqDetails, invalidArtifactUUID, errorInfo, variables, null, true);
+ null, artifactReqDetails, invalidArtifactUUID, errorInfo, variables, null, true);
}
@@ -1819,7 +1814,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
variables = asList("invalidNormalizedName", ComponentTypeEnum.RESOURCE_INSTANCE.getValue().toLowerCase(), ComponentTypeEnum.SERVICE.getValue(), component.getName());
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, true);
+ component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, true);
} else {
component.setUUID("invalidComponentUUID");
@@ -1827,7 +1822,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
variables = asList("null");
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, null, artifactReqDetails, artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, false);
+ null, artifactReqDetails, artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, false);
}
performClean();
@@ -1837,9 +1832,9 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="updateArtifactOnAssetWhichInInvalidStateForUploading", parallel=true)
public static Object[][] dataProviderUpdateProviderDeleteArtifactOnAssetWhichInInvalidStateForUploading() {
return new Object[][] {
- {ComponentTypeEnum.SERVICE, "OTHER"},
- {ComponentTypeEnum.RESOURCE, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, "DCAE_INVENTORY_TOSCA"},
+ {ComponentTypeEnum.SERVICE, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
};
}
@@ -1850,7 +1845,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name());
List<String> variables = asList(component.getName(), component.getComponentType().toString().toLowerCase(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getFirstName(),
ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getLastName(), ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getUserId());
- updateArtifactOnAssetViaExternalAPI(component, componentTypeEnum, LifeCycleStatesEnum.STARTCERTIFICATION, artifactType, errorInfo, variables, UserRoleEnum.DESIGNER, 403);
+ updateArtifactOnAssetViaExternalAPI(component, componentTypeEnum, LifeCycleStatesEnum.STARTCERTIFICATION, artifactType, errorInfo, variables, UserRoleEnum.DESIGNER);
}
@@ -1934,8 +1929,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
-
-
// InvalidArtifact + check audit & response code function
@Test(dataProvider="updateInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI")
public void updateInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState,
@@ -1987,22 +1980,21 @@ public class CRUDExternalAPI extends ComponentBaseTest {
//// // invalid type
//// String artifactType = artifactReqDetails.getArtifactType();
//// artifactReqDetails.setArtifactType("invalidType");
-//// restResponse = uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, 400, componentResourceInstanceDetails);
+//// restResponse = uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails);
//// // empty type
//// artifactReqDetails.setArtifactType("");
-//// restResponse = uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, 400, componentResourceInstanceDetails);
+//// restResponse = uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails);
//// artifactReqDetails.setArtifactType(artifactType);
///////////////////////////////////////////////////////////////////////////////
}
// TODO
// Update artifact with invalid checksum via external API
- protected void updateArtifactWithInvalidCheckSum(Component component, User sdncModifierDetails, String artifactType,
- ComponentInstance componentInstance) throws Exception {
+ protected void updateArtifactWithInvalidCheckSum(Component component, User sdncModifierDetails, String artifactType, ComponentInstance componentInstance) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_INVALID_MD5.name());
List<String> variables = asList();
// uploadArtifactWithInvalidCheckSumOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
-// artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables);
+// artifactReqDetails, componentResourceInstanceDetails, errorInfo, variables);
}
@@ -2011,20 +2003,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
ComponentInstance componentInstance) throws Exception {
ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true);
- String artifactUUID = null;
- Map<String, ArtifactDefinition> deploymentArtifacts;
- if(componentInstance != null) {
- deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts();
- } else {
- deploymentArtifacts = component.getDeploymentArtifacts();
- }
-
- for (String key : deploymentArtifacts.keySet()) {
- if (key.startsWith("ci")) {
- artifactUUID = deploymentArtifacts.get(key).getArtifactUUID();
- break;
- }
- }
+ String artifactUUID = getFirstArtifactUuidFromComponent(component);
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name());
List<String> variables = asList("artifact name", "255");
@@ -2032,10 +2011,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
@@ -2046,20 +2025,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
ComponentInstance componentInstance) throws Exception {
ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true);
- String artifactUUID = null;
- Map<String, ArtifactDefinition> deploymentArtifacts;
- if(componentInstance != null) {
- deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts();
- } else {
- deploymentArtifacts = component.getDeploymentArtifacts();
- }
-
- for (String key : deploymentArtifacts.keySet()) {
- if (key.startsWith("ci")) {
- artifactUUID = deploymentArtifacts.get(key).getArtifactUUID();
- break;
- }
- }
+ String artifactUUID = getFirstArtifactUuidFromComponent(component);
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_ARTIFACT_NAME.name());
List<String> variables = asList();
@@ -2067,80 +2033,56 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
- // Update artifact with valid type & invalid label via external API - label to long
+ // Update artifact with valid type & invalid label via external API - label to long -
+// according to the newest AID doc artifactLabel, artifactType, artifactGroupType parameters should be ignored
protected void updateArtifactWithInvalidLabelToLong(Component component, User sdncModifierDetails, String artifactType,
ComponentInstance componentInstance) throws Exception {
ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true);
- String artifactUUID = null;
- Map<String, ArtifactDefinition> deploymentArtifacts;
- if(componentInstance != null) {
- deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts();
- } else {
- deploymentArtifacts = component.getDeploymentArtifacts();
- }
-
- for (String key : deploymentArtifacts.keySet()) {
- if (key.startsWith("ci")) {
- artifactUUID = deploymentArtifacts.get(key).getArtifactUUID();
- break;
- }
- }
+ String artifactUUID = getFirstArtifactUuidFromComponent(component);
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED.name());
- List<String> variables = asList();
- artifactReqDetails.setArtifactLabel("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
+// ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED.name());
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.OK.name());
+// List<String> variables = asList();
+ artifactReqDetails.setArtifactLabel("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, null, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ null, artifactReqDetails, artifactUUID, errorInfo, null, null, true);
}
}
// Update artifact with valid type & invalid label via external API - label is empty
+// according to the newest AID doc artifactLabel, artifactType, artifactGroupType parameters should be ignored
protected void updateArtifactWithInvalidLabelEmpty(Component component, User sdncModifierDetails, String artifactType,
ComponentInstance componentInstance) throws Exception {
ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true);
- String artifactUUID = null;
- Map<String, ArtifactDefinition> deploymentArtifacts;
- if(componentInstance != null) {
- deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts();
- } else {
- deploymentArtifacts = component.getDeploymentArtifacts();
- }
-
- for (String key : deploymentArtifacts.keySet()) {
- if (key.startsWith("ci")) {
- artifactUUID = deploymentArtifacts.get(key).getArtifactUUID();
- break;
- }
- }
+ String artifactUUID = getFirstArtifactUuidFromComponent(component);
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
- List<String> variables = asList("artifact label");
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.OK.name());
artifactReqDetails.setArtifactLabel("");
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, null, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ null, artifactReqDetails, artifactUUID, errorInfo, null, null, true);
}
}
@@ -2151,44 +2093,26 @@ public class CRUDExternalAPI extends ComponentBaseTest {
ComponentInstance componentInstance) throws Exception {
ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true);
- String artifactUUID = null;
- Map<String, ArtifactDefinition> deploymentArtifacts;
- if(componentInstance != null) {
- deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts();
- } else {
- deploymentArtifacts = component.getDeploymentArtifacts();
- }
-
- for (String key : deploymentArtifacts.keySet()) {
- if (key.startsWith("ci")) {
- artifactUUID = deploymentArtifacts.get(key).getArtifactUUID();
- break;
- }
- }
+ String artifactUUID = getFirstArtifactUuidFromComponent(component);
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED.name());
- List<String> variables = asList();
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name());
+ List<String> variables = asList("artifact description", ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH.toString());
artifactReqDetails.setDescription("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
-
-
- // Update artifact with invalid description via external API - empty description
- protected void updateArtifactWithInvalidDescriptionEmpty(Component component, User sdncModifierDetails, String artifactType,
- ComponentInstance componentInstance) throws Exception {
-
- ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true);
+
+ public String getFirstArtifactUuidFromComponent(Component component) {
String artifactUUID = null;
Map<String, ArtifactDefinition> deploymentArtifacts;
- if(componentInstance != null) {
+ if(component.getComponentInstances() != null) {
deploymentArtifacts = component.getComponentInstances().get(0).getDeploymentArtifacts();
} else {
deploymentArtifacts = component.getDeploymentArtifacts();
@@ -2200,18 +2124,27 @@ public class CRUDExternalAPI extends ComponentBaseTest {
break;
}
}
+ return artifactUUID;
+ }
+
+
+ // Update artifact with invalid description via external API - empty description
+ protected void updateArtifactWithInvalidDescriptionEmpty(Component component, User sdncModifierDetails, String artifactType,
+ ComponentInstance componentInstance) throws Exception {
+ ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", artifactType, true, true);
+ String artifactUUID = getFirstArtifactUuidFromComponent(component);
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED.name());
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
List<String> variables = asList("artifact description");
artifactReqDetails.setDescription("");
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
@@ -2221,7 +2154,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// update artifact via external API + check audit & response code
// Download artifact via external API + check audit & response code
// Check artifact version, uuid & checksusm
- protected Component updateArtifactOnAssetViaExternalAPI(Component component, ComponentTypeEnum componentTypeEnum, LifeCycleStatesEnum chosenLifeCycleState, String artifactType, ErrorInfo errorInfo, List<String> variables, UserRoleEnum userRoleEnum, Integer expectedResponseCode) throws Exception {
+ protected Component updateArtifactOnAssetViaExternalAPI(Component component, ComponentTypeEnum componentTypeEnum, LifeCycleStatesEnum chosenLifeCycleState, String artifactType, ErrorInfo errorInfo, List<String> variables, UserRoleEnum userRoleEnum) throws Exception {
String componentVersionBeforeUpdate = null;
// get updated artifact data
@@ -2239,10 +2172,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// create component/s & upload artifact via external api
if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum),
- expectedResponseCode, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, chosenLifeCycleState, true);
+ component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, chosenLifeCycleState, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum),
- expectedResponseCode, null, artifactReqDetails, artifactUUID, errorInfo, variables, chosenLifeCycleState, true);
+ null, artifactReqDetails, artifactUUID, errorInfo, variables, chosenLifeCycleState, true);
}
if(component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
@@ -2266,7 +2199,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
protected RestResponse updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails,
- Integer expectedResponseCode, ComponentInstance componentInstance, ArtifactReqDetails artifactReqDetails, String artifactUUID, ErrorInfo errorInfo, List<String> variables, LifeCycleStatesEnum lifeCycleStatesEnum, Boolean resourceNameInAudit) throws Exception {
+ ComponentInstance componentInstance, ArtifactReqDetails artifactReqDetails, String artifactUUID, ErrorInfo errorInfo, List<String> variables, LifeCycleStatesEnum lifeCycleStatesEnum, Boolean resourceNameInAudit) throws Exception {
RestResponse restResponse;
if(componentInstance != null) {
@@ -2275,10 +2208,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfTheAsset(component, sdncModifierDetails, artifactReqDetails, artifactUUID);
}
-
// validate response code
Integer responseCode = restResponse.getErrorCode();
- Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct.");
+ Assert.assertEquals(responseCode, errorInfo.getCode(), "Response code is not correct.");
+ component = AtomicOperationUtils.getComponentObject(component, UserRoleEnum.DESIGNER);
//TODO
// Check auditing for upload operation
@@ -2295,7 +2228,12 @@ public class CRUDExternalAPI extends ComponentBaseTest {
expectedExternalAudit.setRESOURCE_NAME(component.getName());
expectedExternalAudit.setRESOURCE_TYPE(component.getComponentType().getValue());
expectedExternalAudit.setARTIFACT_DATA("");
- expectedExternalAudit.setCURR_ARTIFACT_UUID(artifactUUID);
+ if(errorInfo.getCode()==200){
+ expectedExternalAudit.setCURR_ARTIFACT_UUID(responseArtifact.getArtifactUUID());
+ expectedExternalAudit.setARTIFACT_DATA(AuditValidationUtils.buildArtifactDataAudit(responseArtifact));
+ }else{
+ expectedExternalAudit.setCURR_ARTIFACT_UUID(artifactUUID);
+ }
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentInstance != null) {
@@ -2317,11 +2255,9 @@ public class CRUDExternalAPI extends ComponentBaseTest {
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
}
}
-
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body);
return restResponse;
-
}
@@ -2501,26 +2437,26 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="deleteArtifactForServiceViaExternalAPI", parallel=true)
public static Object[][] dataProviderDeleteArtifactForServiceViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML"},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER"},
- {LifeCycleStatesEnum.CERTIFY, "YANG_XML"},
- {LifeCycleStatesEnum.CERTIFY, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CERTIFY, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CERTIFY, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CERTIFY, "OTHER"}
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType()},
+ {LifeCycleStatesEnum.CERTIFY, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CERTIFY, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CERTIFY, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CERTIFY, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CERTIFY, ArtifactTypeEnum.OTHER.getType()}
};
}
@@ -2535,47 +2471,47 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="deleteArtifactForVFViaExternalAPI", parallel=true)
public static Object[][] dataProviderDeleteArtifactForVFViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_JSON"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_POLICY"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_EVENT"},
- {LifeCycleStatesEnum.CHECKOUT, "APPC_CONFIG"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_DOC"},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_TOSCA"},
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE"},
- {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE"},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER"},
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_JSON"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_POLICY"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_EVENT"},
- {LifeCycleStatesEnum.CHECKIN, "APPC_CONFIG"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_DOC"},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_TOSCA"},
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML"},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE"},
- {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE"},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CHECKIN, "OTHER"},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_JSON"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_POLICY"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_EVENT"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "APPC_CONFIG"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_DOC"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_TOSCA"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC"},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER"},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_JSON.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_POLICY.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_EVENT.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.APPC_CONFIG.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_DOC.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_TOSCA.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VF_LICENSE.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VENDOR_LICENSE.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_JSON.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_POLICY.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_EVENT.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.APPC_CONFIG.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_DOC.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_TOSCA.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VF_LICENSE.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VENDOR_LICENSE.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_JSON.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_POLICY.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_EVENT.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.APPC_CONFIG.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_DOC.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_TOSCA.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VF_LICENSE.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VENDOR_LICENSE.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType()},
};
}
@@ -2591,95 +2527,95 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="deleteArtifactForVfcVlCpViaExternalAPI", parallel=true)
public static Object[][] dataProviderDeleteArtifactForVfcVlCpViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CHECKOUT, "YANG_XML", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "OTHER", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.CP},
-
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CHECKIN, "YANG_XML", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "VF_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "VENDOR_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "OTHER", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.CP},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VF_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VENDOR_LICENSE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.CP}
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.YANG_XML.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VNF_CATALOG.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VF_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.MODEL_QUERY_SPEC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.OTHER.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP}
};
}
@@ -2695,26 +2631,26 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="deleteArtifactOnRIViaExternalAPI", parallel=true)
public static Object[][] dataProviderDeleteArtifactOnRIViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", null},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", null},
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", null},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", null},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VF},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VF},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VF},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VF},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VF},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VF}
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), null},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), null},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), null},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), null},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), null},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), null},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), null},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), null},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), null},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), null},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), null},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), null},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VF},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VF},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VF},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VF},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VF},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VF}
};
}
@@ -2734,88 +2670,88 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="deleteArtifactOnVfcVlCpRIViaExternalAPI", parallel=true)
public static Object[][] dataProviderDeleteArtifactOnVfcVlCpRIViaExternalAPI() {
return new Object[][] {
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
-
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP,},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKOUT, "SNMP_TRAP", ResourceTypeEnum.CP},
-
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CHECKIN, "SNMP_TRAP", ResourceTypeEnum.CP},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VFC},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VFC},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.VL},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.VL},
-
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_JSON", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_POLICY", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_DOC", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_BLUEPRINT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "DCAE_INVENTORY_EVENT", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_POLL", ResourceTypeEnum.CP},
- {LifeCycleStatesEnum.CERTIFICATIONREQUEST, "SNMP_TRAP", ResourceTypeEnum.CP}
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.CP,},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP},
+
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VFC},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VFC},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.VL},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.VL},
+
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_POLL.getType(), ResourceTypeEnum.CP},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ArtifactTypeEnum.SNMP_TRAP.getType(), ResourceTypeEnum.CP}
};
}
@@ -2835,51 +2771,51 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="deleteArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset", parallel=true)
public static Object[][] dataProviderDeleteArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset() {
return new Object[][] {
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
-
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"},
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
-
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"},
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
-
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"},
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.DESIGNER2, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.TESTER, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.ADMIN, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.OPS, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
//
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"},
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
-
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"},
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
-
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, "DCAE_INVENTORY_TOSCA"},
- {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, "DCAE_INVENTORY_TOSCA"},
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.GOVERNOR, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_STRATEGIST1, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKIN, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
+ {ComponentTypeEnum.RESOURCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.SERVICE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, UserRoleEnum.PRODUCT_MANAGER1, LifeCycleStatesEnum.CHECKOUT, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
};
}
@@ -2905,10 +2841,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum),
- errorInfo.getCode(), component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, lifeCycleStatesEnum, true);
+ component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, lifeCycleStatesEnum, true);
} else {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum),
- errorInfo.getCode(), null, artifactUUID, errorInfo, variables, lifeCycleStatesEnum, true);
+ null, artifactUUID, errorInfo, variables, lifeCycleStatesEnum, true);
}
//TODO
@@ -2919,9 +2855,9 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="deleteArtifactOnAssetWhichNotExist", parallel=true)
public static Object[][] dataProviderDeleteArtifactOnAssetWhichNotExist() {
return new Object[][] {
- {ComponentTypeEnum.SERVICE, "OTHER", null},
- {ComponentTypeEnum.RESOURCE, "OTHER", null},
- {ComponentTypeEnum.RESOURCE_INSTANCE, "DCAE_INVENTORY_TOSCA", ResourceTypeEnum.VF},
+ {ComponentTypeEnum.SERVICE, ArtifactTypeEnum.OTHER.getType(), null},
+ {ComponentTypeEnum.RESOURCE, ArtifactTypeEnum.OTHER.getType(), null},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), ResourceTypeEnum.VF},
};
}
@@ -2950,10 +2886,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), component.getComponentInstances().get(0), invalidArtifactUUID, errorInfo, variables, null, true);
+ component.getComponentInstances().get(0), invalidArtifactUUID, errorInfo, variables, null, true);
} else {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), null, invalidArtifactUUID, errorInfo, variables, null, true);
+ null, invalidArtifactUUID, errorInfo, variables, null, true);
}
@@ -2964,7 +2900,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER.name());
variables = asList("invalidNormalizedName", ComponentTypeEnum.RESOURCE_INSTANCE.getValue().toLowerCase(), ComponentTypeEnum.SERVICE.getValue(), component.getName());
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, true);
+ component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, true);
} else {
component.setUUID("invalidComponentUUID");
if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE)) {
@@ -2974,7 +2910,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
variables = asList("invalidComponentUUID");
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), null, artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, false);
+ null, artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, false);
}
@@ -2985,9 +2921,9 @@ public class CRUDExternalAPI extends ComponentBaseTest {
@DataProvider(name="deleteArtifactOnAssetWhichInInvalidStateForUploading", parallel=true)
public static Object[][] dataProviderDeleteArtifactOnAssetWhichInInvalidStateForUploading() {
return new Object[][] {
- {ComponentTypeEnum.SERVICE, "OTHER"},
- {ComponentTypeEnum.RESOURCE, "OTHER"},
- {ComponentTypeEnum.RESOURCE_INSTANCE, "DCAE_INVENTORY_TOSCA"},
+ {ComponentTypeEnum.SERVICE, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE, ArtifactTypeEnum.OTHER.getType()},
+ {ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()},
};
}
@@ -3015,10 +2951,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null, true);
+ component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null, true);
} else {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), null, artifactUUID, errorInfo, variables, null, true);
+ null, artifactUUID, errorInfo, variables, null, true);
}
@@ -3038,17 +2974,21 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// Verify that it cannot delete VFC/VL/CP artifact on VFCi/VLi/CPi - Failure flow
@Test(dataProvider="deleteArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI")
public void deleteArtifactOfVfcVlCpForVfciVliCpiViaExternalAPI(ResourceTypeEnum resourceTypeEnum) throws Exception {
+ if(true){
+ throw new SkipException("Open bug 321550");
+ }
+
getExtendTest().log(Status.INFO, String.format("resourceTypeEnum: %s", resourceTypeEnum));
Component resourceInstanceDetails = getComponentInTargetLifeCycleState(ComponentTypeEnum.RESOURCE.getValue(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, resourceTypeEnum);
- ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", "SNMP_TRAP", true, false);
+ ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("ci", ArtifactTypeEnum.SNMP_TRAP.getType(), true, false);
uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceInstanceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, 200);
resourceInstanceDetails = AtomicOperationUtils.changeComponentState(resourceInstanceDetails, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
Component component = getComponentInTargetLifeCycleState(ComponentTypeEnum.RESOURCE.toString(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, null);
AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceInstanceDetails, component, UserRoleEnum.DESIGNER, true).left().value();
component = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, component.getName(), component.getVersion());
- ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name());
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
Map<String, ArtifactDefinition> deploymentArtifacts;
deploymentArtifacts = getDeploymentArtifactsOfAsset(component, ComponentTypeEnum.RESOURCE_INSTANCE);
String artifactUUID = null;
@@ -3060,11 +3000,11 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
List<String> variables = asList(artifactUUID);
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- errorInfo.getCode(), component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null, true);
+ component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null, true);
}
protected RestResponse deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails,
- Integer expectedResponseCode, ComponentInstance componentInstance, String artifactUUID, ErrorInfo errorInfo, List<String> variables, LifeCycleStatesEnum lifeCycleStatesEnum, Boolean resourceNameInAudit) throws Exception {
+ ComponentInstance componentInstance, String artifactUUID, ErrorInfo errorInfo, List<String> variables, LifeCycleStatesEnum lifeCycleStatesEnum, Boolean resourceNameInAudit) throws Exception {
RestResponse restResponse;
if(componentInstance != null) {
@@ -3076,7 +3016,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// validate response code
Integer responseCode = restResponse.getErrorCode();
- Assert.assertEquals(responseCode, expectedResponseCode, "Response code is not correct.");
+ Assert.assertEquals(responseCode, errorInfo.getCode(), "Response code is not correct.");
// Check auditing for upload operation
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java
index 90dd3a47ae..b96abc0e53 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java
@@ -332,8 +332,7 @@ public class GetAssetServlet extends ComponentBaseTest {
ObjectMapper mapper = new ObjectMapper();
try {
- ArtifactUiDownloadData artifactUiDownloadData = mapper.readValue(artifactUiDownloadDataStr,
- ArtifactUiDownloadData.class);
+ ArtifactUiDownloadData artifactUiDownloadData = mapper.readValue(artifactUiDownloadDataStr, ArtifactUiDownloadData.class);
return artifactUiDownloadData;
} catch (Exception e) {
e.printStackTrace();
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/VFCMTExternalAPI.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/VFCMTExternalAPI.java
index 6e212d3155..8da7988ad1 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/VFCMTExternalAPI.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/VFCMTExternalAPI.java
@@ -56,6 +56,7 @@ import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtilsExternalAPI;
import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.openecomp.sdc.common.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
@@ -216,10 +217,6 @@ public class VFCMTExternalAPI extends ComponentBaseTest {
// Various failure flows
@Test(dataProvider="createVfcmtVariousFailureFlows")
public void createVfcmtVariousFailureFlows(String flow) throws Exception {
- //TODO: check what happens now, test will prbably fail
- if(flow.equals("resource_type_missing") || flow.equals("resource_type_invalid")) {
- throw new SkipException("TC require repairs");
- }
User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
ResourceExternalReqDetails defaultResource = ElementFactory.getDefaultResourceByType("ci", ResourceCategoryEnum.TEMPLATE_MONITORING_TEMPLATE, defaultUser.getUserId(), ResourceTypeEnum.VFCMT.toString());
@@ -272,7 +269,7 @@ public class VFCMTExternalAPI extends ComponentBaseTest {
case "description_with_invalid_char":
defaultResource.setDescription("\uC2B5");
expectedResourceAuditJavaObject.setDesc("t");
- errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_RESOURCE_TYPE.name());
+ errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_INVALID_DESCRIPTION.name());
variables = asList(ComponentTypeEnum.RESOURCE.getValue());
break;
// TODO: defect on the flow - need to get error instead create VFC
@@ -319,7 +316,7 @@ public class VFCMTExternalAPI extends ComponentBaseTest {
case "vendor_name_to_long":
defaultResource.setVendorName("asdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdffasdff");
errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT.name());
- variables = asList("25");
+ variables = asList(ValidationUtils.VENDOR_NAME_MAX_LENGTH.toString());
break;
case "vendor_name_with_invalid_char":
defaultResource.setVendorName("!@#$*()&*^%$#@");
diff --git a/test-apis-ci/src/main/resources/ci/scripts/copyToStorage.sh b/test-apis-ci/src/main/resources/ci/scripts/copyToStorage.sh
index 30094fe235..b7b8c09715 100644
--- a/test-apis-ci/src/main/resources/ci/scripts/copyToStorage.sh
+++ b/test-apis-ci/src/main/resources/ci/scripts/copyToStorage.sh
@@ -3,7 +3,6 @@
REPORT_NAME=$1
VERSION=$2
ENV=$3
-IP=$4
if [ -z "$REPORT_NAME" ]
then
@@ -19,6 +18,12 @@ if [ -z "$REPORT_NAME" ]
fi
fi
+
+source conf/attInternal.info
+IP=$automationResutlsRepo
+PASS=$automationResutlsRepoPass
+
+echo ${IP}
/usr/bin/expect << EOF
spawn ssh admin@${IP} mkdir -p -m 775 /home/admin/reports/${ENV}/${VERSION}/APIs/
@@ -29,7 +34,7 @@ expect {
exp_continue
}
-re ".*sword.*" {
- exp_send "Aa123456\r"
+ exp_send ${PASS}\r
}
}
@@ -43,7 +48,7 @@ expect {
exp_continue
}
-re ".*sword.*" {
- exp_send "Aa123456\r"
+ exp_send ${PASS}\r
}
}
@@ -57,7 +62,7 @@ expect {
exp_continue
}
-re ".*sword.*" {
- exp_send "Aa123456\r"
+ exp_send ${PASS}\r
}
}
diff --git a/test-apis-ci/src/main/resources/ci/testSuites/CRUDArtifacts.xml b/test-apis-ci/src/main/resources/ci/testSuites/CRUDArtifacts.xml
index e53da8da8a..923777542c 100644
--- a/test-apis-ci/src/main/resources/ci/testSuites/CRUDArtifacts.xml
+++ b/test-apis-ci/src/main/resources/ci/testSuites/CRUDArtifacts.xml
@@ -5,9 +5,9 @@
<test name="Test">
<classes>
<class
- name="org.openecomp.sdc.ci.tests.execute.devCI.CRUDExternalAPI">
+ name="org.openecomp.sdc.externalApis.CRUDExternalAPI">
<methods>
- <include name="uploadArtifactOnVFViaExternalAPI" />
+ <!-- <include name="uploadArtifactOnVFViaExternalAPI" />
<include name="uploadArtifactOnServiceViaExternalAPI" />
<include name="uploadArtifactOnRIViaExternalAPI" />
<include name="uploadInvalidArtifactTypeExtensionLabelDescriptionCheckSumDuplicateLabelViaExternalAPI" />
@@ -30,7 +30,9 @@
<include name="deleteArtifactOnRIViaExternalAPI" />
<include name="deleteArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset" />
<include name="deleteArtifactOnAssetWhichNotExist" />
- <include name="deleteArtifactOnAssetWhichInInvalidStateForUploading" />
+ <include name="deleteArtifactOnAssetWhichInInvalidStateForUploading" /> -->
+
+ <include name="deleteArtifactForServiceViaExternalAPI" />
</methods>
</class>
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Service_Tests_UI.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Service_Tests_UI.java
index 80801afafb..a4c7ffa632 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Service_Tests_UI.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/Service_Tests_UI.java
@@ -54,7 +54,7 @@ public class Service_Tests_UI extends SetupCDTest{
@Test
public void declareVL_CP_InputsInServiceLevel() throws Exception {
String vnfFile = "FDNT.zip";
- Pair<String,Map<String,String>> VspName =OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser());
+ Pair<String,Map<String,String>> VspName =OnboardingUtils.onboardAndValidate(FileHandling.getVnfRepositoryPath(), vnfFile, getUser());
ServiceReqDetails servicemetadata = ElementFactory.getDefaultService(getUser());
ServiceUIUtils.createService(servicemetadata, getUser());
GeneralUIUtils.moveToStep(StepsEnum.COMPOSITION);
@@ -72,7 +72,7 @@ public class Service_Tests_UI extends SetupCDTest{
@Test
public void CreateServiceWithCpInstance() throws Exception {
String vnfFile = "FDNT.zip";
- Pair<String,Map<String,String>> VspName =OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser());
+ Pair<String,Map<String,String>> VspName =OnboardingUtils.onboardAndValidate(FileHandling.getVnfRepositoryPath(), vnfFile, getUser());
ServiceReqDetails servicemetadata = ElementFactory.getDefaultService(getUser());
ServiceUIUtils.createService(servicemetadata, getUser());
GeneralUIUtils.moveToStep(StepsEnum.COMPOSITION);
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CatalogLeftPanelTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CatalogLeftPanelTest.java
index 519f1e1a76..f0bc6f7505 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CatalogLeftPanelTest.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CatalogLeftPanelTest.java
@@ -22,7 +22,6 @@ package org.openecomp.sdc.ci.tests.execute.sanity;
import static org.testng.AssertJUnit.assertTrue;
-import java.io.File;
import java.util.Arrays;
import java.util.List;
@@ -58,15 +57,7 @@ public class CatalogLeftPanelTest extends SetupCDTest{
private String filePath;
@BeforeMethod
public void beforeTest(){
- filePath = System.getProperty("filepath");
-
- if (filePath == null && System.getProperty("os.name").contains("Windows")) {
- filePath = FileHandling.getResourcesFilesPath();
- }
-
- else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
- filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator;
- }
+ filePath = FileHandling.getFilePath("");
}
public static String[] resourceTypes = Arrays.stream(ResourceTypeEnum.class.getEnumConstants()).
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CustomizationUUID.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CustomizationUUID.java
index 2c2b09af22..b8b7bd752e 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CustomizationUUID.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/CustomizationUUID.java
@@ -20,7 +20,6 @@
package org.openecomp.sdc.ci.tests.execute.sanity;
-import java.io.File;
import java.util.ArrayList;
import java.util.List;
@@ -71,15 +70,7 @@ public class CustomizationUUID extends SetupCDTest {
@BeforeMethod
public void beforeTest(){
- filePath = System.getProperty("filepath");
-
- if (filePath == null && System.getProperty("os.name").contains("Windows")) {
- filePath = FileHandling.getResourcesFilesPath();
- }
-
- else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
- filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator;
- }
+ filePath = FileHandling.getFilePath("");
}
@Test
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/DeploymentViewTests.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/DeploymentViewTests.java
index 2e25eddd2c..1af68d9364 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/DeploymentViewTests.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/DeploymentViewTests.java
@@ -20,10 +20,8 @@
package org.openecomp.sdc.ci.tests.execute.sanity;
-import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
-import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -56,15 +54,7 @@ public class DeploymentViewTests extends SetupCDTest {
@BeforeMethod
public void beforeTest(){
- filePath = System.getProperty("filepath");
-
- if (filePath == null && System.getProperty("os.name").contains("Windows")) {
- filePath = FileHandling.getResourcesFilesPath();
- }
-
- else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
- filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator;
- }
+ filePath = FileHandling.getFilePath("");
}
@DataProvider(name = "CSAR_VF_Files", parallel = false)
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportDCAE.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportDCAE.java
index 6a80dfe854..a26919ae2a 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportDCAE.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportDCAE.java
@@ -22,7 +22,6 @@ package org.openecomp.sdc.ci.tests.execute.sanity;
import static org.testng.AssertJUnit.assertTrue;
-import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -36,11 +35,11 @@ import org.openecomp.sdc.ci.tests.datatypes.ArtifactInfo;
import org.openecomp.sdc.ci.tests.datatypes.CanvasElement;
import org.openecomp.sdc.ci.tests.datatypes.CanvasManager;
import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
-import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.InformationalArtifactsPlaceholders;
import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems;
import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum.ResourceMetadataEnum;
+import org.openecomp.sdc.ci.tests.datatypes.LifeCycleStateEnum;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum;
@@ -50,7 +49,6 @@ import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
import org.openecomp.sdc.ci.tests.pages.CompositionPage;
import org.openecomp.sdc.ci.tests.pages.DeploymentArtifactPage;
-import org.openecomp.sdc.ci.tests.pages.DeploymentPage;
import org.openecomp.sdc.ci.tests.pages.GeneralPageElements;
import org.openecomp.sdc.ci.tests.pages.InformationalArtifactPage;
import org.openecomp.sdc.ci.tests.pages.InputsPage;
@@ -81,18 +79,12 @@ import com.aventstack.extentreports.Status;
public class ImportDCAE extends SetupCDTest {
+ private static final String SERVICE_INPUT_TEST_VF2_CSAR = "service_input_test_VF2.csar";
private String filePath;
+
@BeforeMethod
public void beforeTest(){
- filePath = System.getProperty("filepath");
-
- if (filePath == null && System.getProperty("os.name").contains("Windows")) {
- filePath = FileHandling.getResourcesFilesPath();
- }
-
- else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
- filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator;
- }
+ filePath = FileHandling.getFilePath("");
}
@Test
@@ -159,8 +151,8 @@ public class ImportDCAE extends SetupCDTest {
ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen();
List<ArtifactInfo> deploymentArtifactList = new ArrayList<ArtifactInfo>();
- deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER"));
- deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "YANG_XML"));
+ deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", ArtifactTypeEnum.OTHER.getType()));
+ deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", ArtifactTypeEnum.YANG_XML.getType()));
for (ArtifactInfo deploymentArtifact : deploymentArtifactList) {
DeploymentArtifactPage.clickAddNewArtifact();
ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact);
@@ -186,7 +178,7 @@ public class ImportDCAE extends SetupCDTest {
createDCAEAsset();
ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen();
- ArtifactInfo informationalArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER");
+ ArtifactInfo informationalArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", ArtifactTypeEnum.OTHER.getType());
InformationalArtifactPage.clickAddNewArtifact();
ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact);
@@ -436,7 +428,7 @@ public class ImportDCAE extends SetupCDTest {
ResourceGeneralPage.getLeftMenu().moveToCompositionScreen();
- ArtifactInfo artifact = new ArtifactInfo(filePath, "Heat-File.yaml", "kuku", "artifact3","OTHER");
+ ArtifactInfo artifact = new ArtifactInfo(filePath, "Heat-File.yaml", "kuku", "artifact3",ArtifactTypeEnum.OTHER.getType());
CompositionPage.showDeploymentArtifactTab();
CompositionPage.clickAddArtifactButton();
ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup());
@@ -467,7 +459,7 @@ public class ImportDCAE extends SetupCDTest {
ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen();
- ArtifactInfo deploymentArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER");
+ ArtifactInfo deploymentArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", ArtifactTypeEnum.OTHER.getType());
DeploymentArtifactPage.clickAddNewArtifact();
ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact);
assertTrue(DeploymentArtifactPage.checkElementsCountInTable(1));
@@ -588,7 +580,7 @@ public class ImportDCAE extends SetupCDTest {
@Test
public void removeFileFromGeneralPageDCAEAssetTest() throws Exception{
- String fileName2 = "service_input_test_VF2.csar";
+ String fileName2 = SERVICE_INPUT_TEST_VF2_CSAR;
ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString());
ResourceUIUtils.importVfFromCsarNoCreate(resourceMetaData, filePath, fileName2, getUser());
GeneralPageElements.clickDeleteFile();
@@ -608,7 +600,7 @@ public class ImportDCAE extends SetupCDTest {
ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen();
- ArtifactInfo informationalArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER");
+ ArtifactInfo informationalArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", ArtifactTypeEnum.OTHER.getType());
InformationalArtifactPage.clickAddNewArtifact();
ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact);
@@ -655,15 +647,13 @@ public class ImportDCAE extends SetupCDTest {
@Test
public void validContactAfterCreateDCAEAssetTest() throws Exception{
- String fileName2 = "service_input_test_VF2.csar";
- ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString());
- ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName2, getUser());
+ ResourceReqDetails resourceMetaData = createDCAEAsset();
SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating that userID equal to user that was logged in..."));
- assertTrue("wrong userId", resourceMetaData.getContactId().equals(ResourceGeneralPage.getContactIdText()));
+ assertTrue("Wrong userId", resourceMetaData.getContactId().equals(ResourceGeneralPage.getContactIdText()));
}
public ResourceReqDetails createDCAEAsset() throws Exception{
- String fileName2 = "service_input_test_VF2.csar";
+ String fileName2 = SERVICE_INPUT_TEST_VF2_CSAR;
ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString());
ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName2, getUser());
resourceMetaData.setVersion("0.1");
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportVFCAsset.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportVFCAsset.java
index c129636291..fca568794b 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportVFCAsset.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/ImportVFCAsset.java
@@ -22,7 +22,6 @@ package org.openecomp.sdc.ci.tests.execute.sanity;
import static org.testng.AssertJUnit.assertTrue;
-import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -59,12 +58,9 @@ import org.openecomp.sdc.ci.tests.verificator.VfVerificator;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
-import com.aventstack.extentreports.Status;
-
public class ImportVFCAsset extends SetupCDTest {
private ResourceReqDetails atomicResourceMetaData;
@@ -72,13 +68,7 @@ public class ImportVFCAsset extends SetupCDTest {
private String filePath;
@BeforeClass
public void beforeClass(){
- filePath = System.getProperty("filepath");
- if (filePath == null && System.getProperty("os.name").contains("Windows")) {
- filePath = FileHandling.getResourcesFilesPath();
- }
- else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
- filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator + "";
- }
+ filePath = FileHandling.getFilePath("");
}
@DataProvider(name = "assetFiles", parallel = false)
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Onboard.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Onboard.java
index 2db818948a..0c4802af64 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Onboard.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Onboard.java
@@ -25,6 +25,7 @@ import static org.testng.AssertJUnit.assertTrue;
import java.awt.AWTException;
import java.io.File;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -68,7 +69,7 @@ import com.clearspring.analytics.util.Pair;
public class Onboard extends SetupCDTest {
-
+ protected static String filepath = FileHandling.getVnfRepositoryPath();
protected String makeDistributionValue;
@Parameters({ "makeDistribution" })
@@ -77,8 +78,18 @@ public class Onboard extends SetupCDTest {
makeDistributionValue = makeDistributionReadValue;
}
- public static Object[][] provideData(Object[] fileNamesFromFolder, String filepath) {
- Object[][] arObject = new Object[fileNamesFromFolder.length][];
+// public static Object[][] provideData(Object[] fileNamesFromFolder, String filepath) {
+// Object[][] arObject = new Object[fileNamesFromFolder.length][];
+//
+// int index = 0;
+// for (Object obj : fileNamesFromFolder) {
+// arObject[index++] = new Object[] { filepath, obj };
+// }
+// return arObject;
+// }
+
+ public static Object[][] provideData(List<String> fileNamesFromFolder, String filepath) {
+ Object[][] arObject = new Object[fileNamesFromFolder.size()][];
int index = 0;
for (Object obj : fileNamesFromFolder) {
@@ -86,81 +97,112 @@ public class Onboard extends SetupCDTest {
}
return arObject;
}
-
+
@DataProvider(name = "VNF_List" , parallel = true)
private static final Object[][] VnfList() throws Exception {
- String filepath = getFilePath();
- Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
- System.out.println(String.format("There are %s zip file(s) to test", fileNamesFromFolder.length));
+ List<String> fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+ List<String> exludeVnfList = Arrays.asList("2016-197_vscp_vscp-fw_1610_e2e.zip", "2016-281_vProbes_BE_11_1_f_30_1610_e2e.zip",
+ "2016-282_vProbes_FE_11_1_f_30_1610_e2e.zip", "2016-044_vfw_fnat_30_1607_e2e.zip", "2017-376_vMOG_11_1.zip", "vMOG.zip",
+ "vMRF_USP_AIC3.0_1702.zip", "2016-211_vprobesbe_vprobes_be_30_1610_e2e.zip", "2016-005_vprobesfe_vprobes_fe_30_1607_e2e.zip",
+ "vMRF_RTT.zip", "2016-006_vvm_vvm_30_1607_e2e.zip", "2016-001_vvm_vvm_30_1607_e2e.zip");
+ fileNamesFromFolder.removeAll(exludeVnfList);
+
+ System.out.println(String.format("There are %s zip file(s) to test", fileNamesFromFolder.size()));
return provideData(fileNamesFromFolder, filepath);
}
+// @DataProvider(name = "randomVNF_List", parallel = false)
+// private static final Object[][] randomVnfList() throws Exception {
+// int randomElementNumber = 3; //how many VNFs to onboard randomly
+// String filepath = getFilePath();
+// Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+// Object[] newRandomFileNamesFromFolder = getRandomElements(randomElementNumber, fileNamesFromFolder);
+// System.out.println(String.format("There are %s zip file(s) to test", newRandomFileNamesFromFolder.length));
+// return provideData(newRandomFileNamesFromFolder, filepath);
+// }
+
@DataProvider(name = "randomVNF_List", parallel = false)
private static final Object[][] randomVnfList() throws Exception {
int randomElementNumber = 3; //how many VNFs to onboard randomly
- String filepath = getFilePath();
- Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
- Object[] newRandomFileNamesFromFolder = getRandomElements(randomElementNumber, fileNamesFromFolder);
- System.out.println(String.format("There are %s zip file(s) to test", newRandomFileNamesFromFolder.length));
+ List<String> fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+ List<String> exludeVnfList = Arrays.asList("2016-197_vscp_vscp-fw_1610_e2e.zip", "2016-281_vProbes_BE_11_1_f_30_1610_e2e.zip",
+ "2016-282_vProbes_FE_11_1_f_30_1610_e2e.zip", "2016-044_vfw_fnat_30_1607_e2e.zip", "2017-376_vMOG_11_1.zip", "vMOG.zip",
+ "vMRF_USP_AIC3.0_1702.zip", "2016-211_vprobesbe_vprobes_be_30_1610_e2e.zip", "2016-005_vprobesfe_vprobes_fe_30_1607_e2e.zip",
+ "vMRF_RTT.zip", "2016-006_vvm_vvm_30_1607_e2e.zip", "2016-001_vvm_vvm_30_1607_e2e.zip");
+ fileNamesFromFolder.removeAll(exludeVnfList);
+ List<String> newRandomFileNamesFromFolder = getRandomElements(randomElementNumber, fileNamesFromFolder);
+ System.out.println(String.format("There are %s zip file(s) to test", newRandomFileNamesFromFolder.size()));
return provideData(newRandomFileNamesFromFolder, filepath);
}
-
- private static Object[] getRandomElements(int randomElementNumber, Object[] fileNamesFromFolder) {
- if(fileNamesFromFolder.length == 0 || fileNamesFromFolder.length < randomElementNumber){
+ private static List<String> getRandomElements(int randomElementNumber, List<String> fileNamesFromFolder) {
+ if(fileNamesFromFolder.size() == 0 || fileNamesFromFolder.size() < randomElementNumber){
return null;
}else{
List<Integer> indexList = new ArrayList<>();
- Object[] newRandomFileNamesFromFolder = new Object[randomElementNumber];
- for(int i = 0; i < fileNamesFromFolder.length; i++){
+ List<String> newRandomFileNamesFromFolder = new ArrayList<>();
+ for(int i = 0; i < fileNamesFromFolder.size(); i++){
indexList.add(i);
}
Collections.shuffle(indexList);
Integer[] randomArray = indexList.subList(0, randomElementNumber).toArray(new Integer[randomElementNumber]);
for(int i = 0; i < randomArray.length; i++){
- newRandomFileNamesFromFolder[i] = fileNamesFromFolder[randomArray[i]];
+ newRandomFileNamesFromFolder.add(fileNamesFromFolder.get(randomArray[i]));
}
return newRandomFileNamesFromFolder;
}
}
+
+// private static Object[] getRandomElements(int randomElementNumber, Object[] fileNamesFromFolder) {
+// if(fileNamesFromFolder.length == 0 || fileNamesFromFolder.length < randomElementNumber){
+// return null;
+// }else{
+// List<Integer> indexList = new ArrayList<>();
+// Object[] newRandomFileNamesFromFolder = new Object[randomElementNumber];
+// for(int i = 0; i < fileNamesFromFolder.length; i++){
+// indexList.add(i);
+// }
+// Collections.shuffle(indexList);
+// Integer[] randomArray = indexList.subList(0, randomElementNumber).toArray(new Integer[randomElementNumber]);
+// for(int i = 0; i < randomArray.length; i++){
+// newRandomFileNamesFromFolder[i] = fileNamesFromFolder[randomArray[i]];
+// }
+// return newRandomFileNamesFromFolder;
+// }
+// }
- public static String getFilePath() {
- String filepath = System.getProperty("filepath");
- if (filepath == null && System.getProperty("os.name").contains("Windows")) {
- filepath = FileHandling.getResourcesFilesPath() +"VNFs";
- }
-
- else if(filepath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
- filepath = FileHandling.getBasePath() + File.separator + "Files" + File.separator +"VNFs";
- }
- return filepath;
- }
+// public static String getFilePath() {
+// String filepath = System.getProperty("filepath");
+// if (filepath == null && System.getProperty("os.name").contains("Windows")) {
+// filepath = FileHandling.getResourcesFilesPath() +"VNFs";
+// }
+//
+// else if(filepath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
+// filepath = FileHandling.getBasePath() + File.separator + "Files" + File.separator +"VNFs";
+// }
+// return filepath;
+// }
@Test
public void onboardVNFTestSanity() throws Exception, Throwable {
- String filepath = getFilePath();
// String vnfFile = "2016-012_vMX_AV_30_1072_e2e.zip";
// String filepath = getFilePath();
- Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
- String vnfFile = fileNamesFromFolder[0].toString();
+// Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+ List<String> fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+ List<String> exludeVnfList = Arrays.asList("2016-197_vscp_vscp-fw_1610_e2e.zip", "2016-281_vProbes_BE_11_1_f_30_1610_e2e.zip",
+ "2016-282_vProbes_FE_11_1_f_30_1610_e2e.zip", "2016-044_vfw_fnat_30_1607_e2e.zip", "2017-376_vMOG_11_1.zip", "vMOG.zip",
+ "vMRF_USP_AIC3.0_1702.zip", "2016-211_vprobesbe_vprobes_be_30_1610_e2e.zip", "2016-005_vprobesfe_vprobes_fe_30_1607_e2e.zip",
+ "vMRF_RTT.zip", "2016-006_vvm_vvm_30_1607_e2e.zip", "2016-001_vvm_vvm_30_1607_e2e.zip");
+ fileNamesFromFolder.removeAll(exludeVnfList);
+ String vnfFile = fileNamesFromFolder.get(0).toString();
runOnboardToDistributionFlow(filepath, vnfFile);
}
public void runOnboardToDistributionFlow(String filepath, String vnfFile) throws Exception, AWTException {
- Pair<String,Map<String,String>> onboardAndValidate = OnboardingUtils.onboardAndValidate(filepath, vnfFile, getUser());
- String vspName = onboardAndValidate.left;
-
- DeploymentArtifactPage.getLeftPanel().moveToCompositionScreen();
- ExtentTestActions.addScreenshot(Status.INFO, "TopologyTemplate_" + vnfFile ,"The topology template for " + vnfFile + " is as follows : ");
-
- DeploymentArtifactPage.clickSubmitForTestingButton(vspName);
-
- reloginWithNewRole(UserRoleEnum.TESTER);
- GeneralUIUtils.findComponentAndClick(vspName);
- TesterOperationPage.certifyComponent(vspName);
+ String vspName = onboardAndCertify(filepath, vnfFile);
reloginWithNewRole(UserRoleEnum.DESIGNER);
// create service
@@ -207,6 +249,24 @@ public class Onboard extends SetupCDTest {
getExtendTest().log(Status.INFO, String.format("The onboarding %s test is passed ! ", vnfFile));
}
+ public String onboardAndCertify(String filepath, String vnfFile) throws Exception, IOException {
+ Pair<String,Map<String,String>> onboardAndValidate = OnboardingUtils.onboardAndValidate(filepath, vnfFile, getUser());
+ String vspName = onboardAndValidate.left;
+
+ DeploymentArtifactPage.getLeftPanel().moveToCompositionScreen();
+ ExtentTestActions.addScreenshot(Status.INFO, "TopologyTemplate_" + vnfFile ,"The topology template for " + vnfFile + " is as follows : ");
+
+ DeploymentArtifactPage.clickSubmitForTestingButton(vspName);
+
+ reloginWithNewRole(UserRoleEnum.TESTER);
+ GeneralUIUtils.findComponentAndClick(vspName);
+ TesterOperationPage.certifyComponent(vspName);
+ return vspName;
+ }
+
+
+
+
// protected synchronized void validateInputArtsVSouput(String serviceName) {
//
//
@@ -225,21 +285,29 @@ public class Onboard extends SetupCDTest {
System.out.println("printttttttttttttt - >" + makeDistributionValue);
runOnboardToDistributionFlow(filepath, vnfFile);
}
+
+ @Test(dataProvider = "VNF_List")
+ public void onboardVNFShotFlow(String filepath, String vnfFile) throws Exception, Throwable {
+ setLog(vnfFile);
+ System.out.println("printttttttttttttt - >" + makeDistributionValue);
+ onboardAndCertify(filepath, vnfFile);
+ }
@Test(dataProvider = "randomVNF_List")
public void onboardRandomVNFsTest(String filepath, String vnfFile) throws Exception, Throwable {
setLog(vnfFile);
System.out.println("printttttttttttttt - >" + makeDistributionValue);
- System.out.println("vnf File name is: " + vnfFile);
+ System.out.println("Vnf File name is: " + vnfFile);
runOnboardToDistributionFlow(filepath, vnfFile);
}
@Test
public void onboardUpdateVNFTest() throws Exception, Throwable {
- String filepath = getFilePath();
- Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
- String vnfFile = fileNamesFromFolder[0].toString();
+// Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+ List<String> fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+// String vnfFile = fileNamesFromFolder[0].toString();
+ String vnfFile = fileNamesFromFolder.get(0);
Pair<String,Map<String,String>> vsp = OnboardingUtils.onboardAndValidate(filepath, vnfFile, getUser());
String vspName = vsp.left;
@@ -264,7 +332,8 @@ public class Onboard extends SetupCDTest {
HomePage.navigateToHomePage();
///update flow
- String updatedVnfFile = fileNamesFromFolder[1].toString();
+// String updatedVnfFile = fileNamesFromFolder[1].toString();
+ String updatedVnfFile = fileNamesFromFolder.get(1);
getExtendTest().log(Status.INFO, String.format("Going to update the VNF with %s......", updatedVnfFile));
// update VendorSoftwareProduct
@@ -309,15 +378,13 @@ public class Onboard extends SetupCDTest {
OpsOperationPage.waitUntilArtifactsDistributed(0);
- getExtendTest().log(Status.INFO, String.format("onboarding %s test is passed ! ", vnfFile));
+ getExtendTest().log(Status.INFO, String.format("Onboarding %s test is passed ! ", vnfFile));
}
@Test
public void threeVMMSCsInServiceTest() throws Exception{
- String filepath = getFilePath();
-
List<String> vmmscList = new ArrayList<String>();
vmmscList = Arrays.asList(new File(filepath).list()).stream().filter(e -> e.contains("vmmsc") && e.endsWith(".zip")).collect(Collectors.toList());
@@ -325,15 +392,15 @@ public class Onboard extends SetupCDTest {
Map<String, String> vspNames = new HashMap<String, String>();
for (String vnfFile : vmmscList){
- getExtendTest().log(Status.INFO, String.format("going to onboard the VNF %s......", vnfFile));
- System.out.println(String.format("going to onboard the VNF %s......", vnfFile));
+ getExtendTest().log(Status.INFO, String.format("Going to onboard the VNF %s......", vnfFile));
+ System.out.println(String.format("Going to onboard the VNF %s......", vnfFile));
AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUtils.createVendorLicense(getUser());
Pair<String,Map<String,String>> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(vnfFile, filepath, getUser(), amdocsLicenseMembers);
- getExtendTest().log(Status.INFO, String.format("searching for onboarded %s", vnfFile));
+ getExtendTest().log(Status.INFO, String.format("Searching for onboarded %s", vnfFile));
HomePage.showVspRepository();
- getExtendTest().log(Status.INFO,String.format("going to import %s......", vnfFile.substring(0, vnfFile.indexOf("."))));
+ getExtendTest().log(Status.INFO,String.format("Going to import %s......", vnfFile.substring(0, vnfFile.indexOf("."))));
OnboardingUtils.importVSP(createVendorSoftwareProduct);
ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen();
@@ -391,19 +458,6 @@ public class Onboard extends SetupCDTest {
}
-
-
-
-
-
-
-
-
-
-
-
-
-
@Override
protected UserRoleEnum getRole() {
return UserRoleEnum.DESIGNER;
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java
index 71fe44cc79..2ce944d273 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java
@@ -28,6 +28,7 @@ import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -67,8 +68,8 @@ public class OnboardViaApis{
private static final String FULL_PATH = "C://tmp//CSARs//";
- public static Object[][] provideData(Object[] fileNamesFromFolder, String filepath) {
- Object[][] arObject = new Object[fileNamesFromFolder.length][];
+ public static Object[][] provideData(List<String> fileNamesFromFolder, String filepath) {
+ Object[][] arObject = new Object[fileNamesFromFolder.size()][];
int index = 0;
for (Object obj : fileNamesFromFolder) {
@@ -81,8 +82,14 @@ public class OnboardViaApis{
private static final Object[][] VnfList() throws Exception {
String filepath = FileHandling.getVnfRepositoryPath();
- Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
- System.out.println(String.format("There are %s zip file(s) to test", fileNamesFromFolder.length));
+// Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+ List<String> fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+ List<String> exludeVnfList = Arrays.asList("2016-197_vscp_vscp-fw_1610_e2e.zip", "2016-281_vProbes_BE_11_1_f_30_1610_e2e.zip",
+ "2016-282_vProbes_FE_11_1_f_30_1610_e2e.zip", "2016-044_vfw_fnat_30_1607_e2e.zip", "2017-376_vMOG_11_1.zip", "vMOG.zip",
+ "vMRF_USP_AIC3.0_1702.zip", "2016-211_vprobesbe_vprobes_be_30_1610_e2e.zip", "2016-005_vprobesfe_vprobes_fe_30_1607_e2e.zip",
+ "vMRF_RTT.zip", "2016-006_vvm_vvm_30_1607_e2e.zip", "2016-001_vvm_vvm_30_1607_e2e.zip");
+ fileNamesFromFolder.removeAll(exludeVnfList);
+ System.out.println(String.format("There are %s zip file(s) to test", fileNamesFromFolder.size()));
return provideData(fileNamesFromFolder, filepath);
}
@@ -126,8 +133,9 @@ public class OnboardViaApis{
public void onboardingAndParser() throws Exception {
Service service = null;
String filepath = getFilePath();
- Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
- String vnfFile = fileNamesFromFolder[7].toString();
+// Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+ List<String> fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+ String vnfFile = fileNamesFromFolder.get(7);
System.err.println(timestamp + " Starting test with VNF: " + vnfFile);
service = runOnboardViaApisOnly(filepath, vnfFile);
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Product.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Product.java
index e0e13b7036..c12a8f220a 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Product.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Product.java
@@ -20,8 +20,6 @@
package org.openecomp.sdc.ci.tests.execute.sanity;
-import java.io.File;
-
import org.openecomp.sdc.ci.tests.datatypes.CanvasElement;
import org.openecomp.sdc.ci.tests.datatypes.CanvasManager;
import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
@@ -32,12 +30,10 @@ import org.openecomp.sdc.ci.tests.pages.CompositionPage;
import org.openecomp.sdc.ci.tests.pages.GeneralPageElements;
import org.openecomp.sdc.ci.tests.pages.ProductGeneralPage;
import org.openecomp.sdc.ci.tests.pages.TesterOperationPage;
-import org.openecomp.sdc.ci.tests.utilities.FileHandling;
import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
import org.openecomp.sdc.ci.tests.utilities.ProductUIUtils;
import org.openecomp.sdc.ci.tests.utilities.ServiceUIUtils;
import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
-import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
@@ -47,21 +43,7 @@ import org.testng.annotations.Test;
public class Product extends SetupCDTest {
- private String filePath;
- @BeforeMethod
- public void beforeTest(){
- filePath = System.getProperty("filepath");
-
- if (filePath == null && System.getProperty("os.name").contains("Windows")) {
- filePath = FileHandling.getResourcesFilesPath();
- }
-
- else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
- filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator;
- }
- }
-
@Test
public void createProductAndAddCertifiedServiceInstance() throws Exception {
ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java
index 3a42d22d0e..9b4d97e0a7 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Service.java
@@ -372,6 +372,10 @@ public class Service extends SetupCDTest {
@Test
public void addDeploymentArtifactToVFInstanceTest() throws Exception{
+ if(true){
+ throw new SkipException("Open bug 321669");
+ }
+
ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL,ArtifactTypeEnum.SNMP_POLL.getType());
@@ -401,6 +405,10 @@ public class Service extends SetupCDTest {
@Test
public void deleteDeploymentArtifactFromVFInstanceNextVersionTest() throws Exception{
+ if(true){
+ throw new SkipException("Open bug 322930");
+ }
+
ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL,ArtifactTypeEnum.SNMP_POLL.getType());
@@ -426,6 +434,10 @@ public class Service extends SetupCDTest {
@Test
public void updateDeploymentArtifactOnVFInstanceNextVersionTest() throws Exception{
+ if(true){
+ throw new SkipException("Open bug 322930");
+ }
+
ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService();
ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL,ArtifactTypeEnum.SNMP_POLL.getType());
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java
index f8ad51ca14..9eee0e9096 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VFCArtifacts.java
@@ -22,7 +22,6 @@ package org.openecomp.sdc.ci.tests.execute.sanity;
import static org.testng.Assert.assertTrue;
-import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
@@ -66,16 +65,9 @@ public class VFCArtifacts extends SetupCDTest {
private static final String ARTIFACTS = "artifacts";
private static final String DEPLOYMENT_ARTIFACTS = "deploymentArtifacts";
private String filePath;
- private Object object;
@BeforeClass
public void beforeClass(){
- filePath = System.getProperty("filepath");
- if (filePath == null && System.getProperty("os.name").contains("Windows")) {
- filePath = FileHandling.getResourcesFilesPath() + "VFCArtifacts"+ File.separator;
- }
- else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
- filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator + "VFCArtifacts"+ File.separator;
- }
+ filePath = FileHandling.getFilePath("");
}
@Test
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java
index ef7a534ee9..8763d677dd 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java
@@ -92,13 +92,7 @@ public class Vf extends SetupCDTest {
private String filePath;
@BeforeClass
public void beforeClass(){
- filePath = System.getProperty("filepath");
- if (filePath == null && System.getProperty("os.name").contains("Windows")) {
- filePath = FileHandling.getResourcesFilesPath();
- }
- else if(filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
- filePath = FileHandling.getBasePath() + File.separator + "Files" + File.separator;
- }
+ filePath = FileHandling.getFilePath("");
}
@BeforeMethod
@@ -519,7 +513,7 @@ public class Vf extends SetupCDTest {
}
@Test
- public void addDeploymentArtifactAndVerifyInCompositionScreen() throws Exception{
+ public void addDeploymentArtifactAndVerifyInCompositionScreen() throws Exception{
ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
ResourceUIUtils.createResource(vfMetaData, getUser());
@@ -653,7 +647,7 @@ public class Vf extends SetupCDTest {
@Test
public void exportToscaWithModulePropertiesVFTest() throws AWTException, Exception {
String vnfFile = "2016-042_vmsp_pxmc_30_1607_e2e.zip";
- Pair<String, Map<String, String>> vsp=OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser());
+ Pair<String, Map<String, String>> vsp=OnboardingUtils.onboardAndValidate(FileHandling.getVnfRepositoryPath(), vnfFile, getUser());
String vspName = vsp.left;
ResourceGeneralPage.clickSubmitForTestingButton(vsp.left);
Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "0.1");
@@ -663,7 +657,7 @@ public class Vf extends SetupCDTest {
@Test
public void exportToscaWithModulePropertiesTemplateCheckVFTest() throws AWTException, Exception {
String vnfFile = "2016-042_vmsp_pxmc_30_1607_e2e.zip";
- OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser());
+ OnboardingUtils.onboardAndValidate(FileHandling.getVnfRepositoryPath(), vnfFile, getUser());
ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen();
GeneralUIUtils.clickOnElementByTestId(ToscaArtifactsScreenEnum.TOSCA_MODEL.getValue());
File latestFilefromDir = FileHandling.getLastModifiedFileFromDir();
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfArtifacts.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfArtifacts.java
index cf8bfa5e5e..86e81df0bb 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfArtifacts.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfArtifacts.java
@@ -206,7 +206,7 @@ public class VfArtifacts extends SetupCDTest{
String vnfFile = "2016-043_vsaegw_fdnt_30_1607_e2e.zip";
String downloadDirPath=SetupCDTest.getConfig().getWindowsDownloadDirectory();
- Pair<String, Map<String, String>> vsp=OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser());
+ Pair<String, Map<String, String>> vsp=OnboardingUtils.onboardAndValidate(FileHandling.getVnfRepositoryPath(), vnfFile, getUser());
Map<String, File> currentZipEnvfiles=ArtifactBusinessLogic.createEnvFilesListFromCsar(vsp.left,downloadDirPath);
GeneralUIUtils.findComponentAndClick(vsp.left);
@@ -231,7 +231,7 @@ public class VfArtifacts extends SetupCDTest{
String downloadDirPath=SetupCDTest.getConfig().getWindowsDownloadDirectory();
String vnfFile = "2016-043_vsaegw_fdnt_30_1607_e2e.zip";
- Pair<String, Map<String, String>> vsp=OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser());
+ Pair<String, Map<String, String>> vsp=OnboardingUtils.onboardAndValidate(FileHandling.getVnfRepositoryPath(), vnfFile, getUser());
Map<String, File> currentZipEnvfiles=ArtifactBusinessLogic.createEnvFilesListFromCsar(vsp.left,downloadDirPath);
GeneralUIUtils.findComponentAndClick(vsp.left);
ResourceGeneralPage.getLeftMenu().moveToCompositionScreen();
@@ -255,7 +255,7 @@ public class VfArtifacts extends SetupCDTest{
String vnfFile = "2016-044_vfw_fcgi_30_1607_e2e.zip";
String downloadDirPath=SetupCDTest.getConfig().getWindowsDownloadDirectory();
- Pair<String, Map<String, String>> CreatedVsp=OnboardingUtils.onboardAndValidate(Onboard.getFilePath(), vnfFile, getUser());
+ Pair<String, Map<String, String>> CreatedVsp=OnboardingUtils.onboardAndValidate(FileHandling.getVnfRepositoryPath(), vnfFile, getUser());
Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, CreatedVsp.left, "0.1");
Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts();
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java
index 22396ec9c7..24badb3ec2 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java
@@ -62,10 +62,9 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String folder ="US825779";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1"));
-
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null);
}
@@ -78,15 +77,15 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String folder ="US825779";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName3.yaml", null, "HeatVolArtifactName3", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName3.yaml", null, "HeatVolArtifactName3", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName,folder, deploymentArtifacts, null);
}
@@ -104,11 +103,11 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String folder ="US825779";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>();
- informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts);
}
@@ -126,13 +125,13 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String folder ="US825779";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>();
- informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
- informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1"));
- informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts);
}
@@ -150,18 +149,18 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String folder ="US825779";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName3.yaml", null, "HeatVolArtifactName3", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName3.yaml", null, "HeatVolArtifactName3", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>();
- informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
- informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1"));
- informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts);
}
@@ -181,9 +180,9 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String folder ="US825779";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "ArtifactName.yaml", null, "ArtifactName", ArtifactTypeEnum.OTHER.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "ArtifactName.yaml", null, "ArtifactName", ArtifactTypeEnum.OTHER.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null);
}
@@ -201,11 +200,11 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String folder ="US825779";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>();
- informationalArtifacts.add(new ArtifactInfo(null, "ArtifactName.yaml", null, "ArtifactName", ArtifactTypeEnum.OTHER.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "ArtifactName.yaml", null, "ArtifactName", ArtifactTypeEnum.OTHER.getType(), "1"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts);
}
@@ -266,15 +265,15 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "4"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "4"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null);
GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1");
fileName = "UpdateTC1443736.csar";
- deploymentArtifacts.add(new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1"));
updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, deploymentArtifacts, null, null, null);
}
@@ -289,9 +288,9 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "4"));
- ArtifactInfo artifactInfo = new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1");
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "4"));
+ ArtifactInfo artifactInfo = new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1");
deploymentArtifacts.add(artifactInfo);
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null);
@@ -316,9 +315,9 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "4"));
- ArtifactInfo artifactInfo = new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1");
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "4"));
+ ArtifactInfo artifactInfo = new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1");
deploymentArtifacts.add(artifactInfo);
@@ -345,8 +344,8 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String folder ="US825779";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null);
@@ -355,7 +354,7 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
fileName = "UpdateTC1443887.csar";
List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>();
- informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, deploymentArtifacts, informationalArtifacts, null, null);
}
@@ -373,11 +372,11 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String fileName = "ImportTC1443888.csar";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>();
- ArtifactInfo artifactInfo = new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1");
+ ArtifactInfo artifactInfo = new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1");
informationalArtifacts.add(artifactInfo);
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts);
@@ -407,11 +406,11 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String fileName = "ImportTC1443890.csar";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>();
- ArtifactInfo artifactInfo = new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1");
+ ArtifactInfo artifactInfo = new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1");
informationalArtifacts.add(artifactInfo);
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts);
@@ -437,18 +436,18 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String fileName = "ImportUpdateTC1443893.csar";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
- deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName3.yaml", null, "HeatVolArtifactName3", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName3.yaml", null, "HeatVolArtifactName3", ArtifactTypeEnum.HEAT_VOL.getType(), "1"));
List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>();
- informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
- informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1"));
- informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts);
@@ -471,12 +470,12 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String folder ="US825779";
String fileName = "ImportTC1443954.csar";
- ArtifactInfo deploymentHeat1 = new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1");
- ArtifactInfo deploymentHeat2 = new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1");
- ArtifactInfo deploymentHeat3 = new ArtifactInfo(null, "heatartifactname3.yaml", null, "heatartifactname3", ArtifactTypeEnum.HEAT.getType(), "1");
+ ArtifactInfo deploymentHeat1 = new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1");
+ ArtifactInfo deploymentHeat2 = new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1");
+ ArtifactInfo deploymentHeat3 = new ArtifactInfo(null, "heatartifactname3.yaml", null, "heatartifactname3", ArtifactTypeEnum.HEAT.getType(), "1");
- ArtifactInfo deploymentHeatVol1 = new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1");
- ArtifactInfo deploymentHeatVol2 = new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1");
+ ArtifactInfo deploymentHeatVol1 = new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1");
+ ArtifactInfo deploymentHeatVol2 = new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1");
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
deploymentArtifacts.add(deploymentHeat1);
@@ -485,12 +484,12 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
deploymentArtifacts.add(deploymentHeatVol1);
deploymentArtifacts.add(deploymentHeatVol2);
- ArtifactInfo infoGuide1 = new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1");
- ArtifactInfo infoGuide2 = new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1");
+ ArtifactInfo infoGuide1 = new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1");
+ ArtifactInfo infoGuide2 = new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1");
- ArtifactInfo infoOther1 = new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1");
- ArtifactInfo infoOther2 = new ArtifactInfo(null, "artifactname2.txt", null, "artifactname2", ArtifactTypeEnum.OTHER.getType(), "1");
- ArtifactInfo infoOther3 = new ArtifactInfo(null, "artifactname3.txt", null, "artifactname3", ArtifactTypeEnum.OTHER.getType(), "1");
+ ArtifactInfo infoOther1 = new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1");
+ ArtifactInfo infoOther2 = new ArtifactInfo(null, "artifactname2.txt", null, "artifactname2", ArtifactTypeEnum.OTHER.getType(), "1");
+ ArtifactInfo infoOther3 = new ArtifactInfo(null, "artifactname3.txt", null, "artifactname3", ArtifactTypeEnum.OTHER.getType(), "1");
List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>();
informationalArtifacts.add(infoGuide1);
@@ -513,8 +512,8 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
deploymentArtifactsNotExist.add(deploymentHeat2);
deploymentArtifacts.remove(deploymentHeat1);
deploymentArtifacts.remove(deploymentHeat2);
- deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname4.yaml", null, "heatartifactname4", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname5.yaml", null, "heatartifactname5", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname4.yaml", null, "heatartifactname4", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname5.yaml", null, "heatartifactname5", ArtifactTypeEnum.HEAT.getType(), "1"));
deploymentHeatVol1.setArtifactVersion("2");
deploymentHeatVol2.setArtifactVersion("2");
@@ -525,8 +524,8 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
informationalArtifactsNotExist.add(infoOther2);
informationalArtifacts.remove(infoGuide2);
informationalArtifacts.remove(infoOther2);
- informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact3.yml", null, "GuideInfoArtifact3", ArtifactTypeEnum.GUIDE.getType(), "1"));
- informationalArtifacts.add(new ArtifactInfo(null, "artifactname4.txt", null, "artifactname4", ArtifactTypeEnum.OTHER.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact3.yml", null, "GuideInfoArtifact3", ArtifactTypeEnum.GUIDE.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "artifactname4.txt", null, "artifactname4", ArtifactTypeEnum.OTHER.getType(), "1"));
updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, deploymentArtifacts, informationalArtifacts, deploymentArtifactsNotExist, informationalArtifactsNotExist);
}
@@ -538,11 +537,10 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
public void updateWithExistedDeploymentArtifactByArtifactWithDifferentType() throws Exception {
String folder ="US825779";
String fileName = "ImportTC1444206.csar";
-
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
- deploymentArtifacts.add(new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null);
@@ -571,11 +569,11 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String fileName = "ImportTC1444207.csar";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>();
- informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts);
@@ -595,14 +593,14 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
// US825779 - Story: [BE] Import VSP - VF informational artifacts - Update
// TC1444208 - Update With Existed Informational Artifact By Deployment Artifact With Different Type
@Test
- public void updateWithExistedInformationalArtifactByDeploymentArtifactWithDifferentType() throws Exception {
+ public void updateWithExistedInformationalArtifactByDeploymentArtifactWithDifferentType() throws Exception {
String folder ="US825779";
String fileName = "ImportTC1444208.csar";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
- deploymentArtifacts.add(new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null);
@@ -679,15 +677,15 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null);
GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1");
fileName = "UpdateTC1444530.csar";
- deploymentArtifacts.add(new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, deploymentArtifacts, null, null, null);
}
@@ -712,7 +710,7 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
fileName = "UpdateTC1444531.csar";
List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>();
- informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
+ informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"));
updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, null, informationalArtifacts, null, null);
}
@@ -724,8 +722,8 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String folder = "US824719";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null);
}
@@ -735,14 +733,15 @@ public class VfDeploymentInformationalArtifacts extends SetupCDTest {
String fileName = "ImportTC1444533.csar";
String folder = "US824719";
String filePath = FileHandling.getFilePath(folder);
+
ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser());
ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser());
String updatedCsarFileName = "UpdateTC1444533.csar";
List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>();
- deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
- deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "4"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "2"));
+ deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "4"));
updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, updatedCsarFileName, deploymentArtifacts, null, null, null);
}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/DriverFactory.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/DriverFactory.java
index 705f0decaf..fd53249ac2 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/DriverFactory.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/DriverFactory.java
@@ -37,6 +37,8 @@ import org.openecomp.sdc.ci.tests.utilities.FileHandling;
import org.openecomp.sdc.ci.tests.utils.Utils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
+import org.testng.ITestContext;
+import org.testng.ITestResult;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
@@ -96,7 +98,7 @@ public class DriverFactory {
webDriverThread.quitDriver();
}
-// MobProxy.removeAllProxyServers();
+ MobProxy.removeAllProxyServers();
deleteDownloadDirs();
}
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java
index 820c6997f5..10ae6cba7a 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/setup/SetupCDTest.java
@@ -238,7 +238,7 @@ public abstract class SetupCDTest extends DriverFactory {
}
}
- public void generateReport4Jenkins(ITestResult result, ITestContext context) {
+ public void generateReport4Jenkins(ITestContext context) {
String suiteName = ExtentManager.getSuiteName(context);
// String outputDirectory = context.getOutputDirectory();
JSONObject obj = new JSONObject();
@@ -269,16 +269,17 @@ public abstract class SetupCDTest extends DriverFactory {
@AfterSuite(alwaysRun = true)
- public void afterSuite(ITestResult result, ITestContext context) throws Exception {
-
- if (getConfig().getUseBrowserMobProxy()){
- MobProxy.getPoxyServer().stop();
- }
+
+ public void afterSuite2() throws Exception {
+// public void afterSuite() throws Exception {
csvReport.closeFile();
- generateReport4Jenkins(result, context);
+ generateReport4Jenkins(myContext);
RestCDUtils.deleteOnDemand();
+ if (getConfig().getUseBrowserMobProxy()){
+ MobProxy.getPoxyServer().stop();
+ }
}
protected static String setUrl() {
@@ -299,7 +300,7 @@ public abstract class SetupCDTest extends DriverFactory {
}
File credentialsFileRemote = new File(FileHandling.getBasePath() + File.separator + "conf" + File.separator + CREDENTIALS_FILE);
// File credentialsFileLocal = new File(FileHandling.getConfFilesPath() + CREDENTIALS_FILE);
- File credentialsFileLocal = new File(FileHandling.getSdcVncPath() + File.separator + "conf"
+ File credentialsFileLocal = new File(FileHandling.getSdcVnfsPath() + File.separator + "conf"
+ File.separator + CREDENTIALS_FILE);
File[] credentialFiles = {credentialsFileRemote, credentialsFileLocal};
for (File credentialsFile : credentialFiles){
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java
index 496c537d49..264971e2d9 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/pages/CompositionPage.java
@@ -146,7 +146,7 @@ public class CompositionPage extends GeneralPageElements {
public static List<WebElement> getOpenTabTitle() throws Exception{
// return GeneralUIUtils.getElementsByCSS("expand-collapse span");
- return GeneralUIUtils.getElementsByCSS("expand-collapse");
+ return GeneralUIUtils.getElementsByCSS("expand-collapse ng-transclude");
}
public static void clickOnTab(DataTestIdEnum.CompositionScreenEnum tabSelector) throws Exception{
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java
index a83e26d980..3c141d3a43 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/FileHandling.java
@@ -109,12 +109,10 @@ public class FileHandling {
return System.getProperty("user.dir") + File.separator;
}
- public static String getSdcVncPath() {
- return Paths.get(System.getProperty("user.dir"), "..", "..", "sdc-vnfs").toString();
+ public static String getSdcVnfsPath() {
+ return getBasePath() + Paths.get("..", "..", "sdc-vnfs").toString();
}
-
-
public static String getDriversPath() {
return getBasePath() + "src" + File.separator + "main" + File.separator + "resources"
+ File.separator + "ci" + File.separator + "drivers" + File.separator;
@@ -124,8 +122,7 @@ public class FileHandling {
// return getBasePath() + "src" + File.separator + "main" + File.separator + "resources"
// + File.separator + "Files" + File.separator;
- return getSdcVncPath()+ File.separator + "ui-tests"
- + File.separator + "Files" + File.separator;
+ return getSdcVnfsPath()+ File.separator + "ui-tests" + File.separator + "Files" + File.separator;
}
public static String getResourcesEnvFilesPath() {
@@ -182,6 +179,30 @@ public class FileHandling {
return null;
}
+ public static List<String> filterFileNamesListFromFolder(String filepath, String extension) {
+ try {
+ File dir = new File(filepath);
+ List<String> filenames = new ArrayList<String>();
+
+ FilenameFilter extensionFilter = new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return name.endsWith(extension);
+ }
+ };
+
+ if (dir.isDirectory()) {
+ for (File file : dir.listFiles(extensionFilter)) {
+ filenames.add(file.getName());
+ }
+ return filenames;
+ }
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
public static String[] getArtifactsFromZip(String filepath, String zipFilename){
try{
ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename);
@@ -214,8 +235,12 @@ public class FileHandling {
}
- public static Object[] getZipFileNamesFromFolder(String filepath) {
- return filterFileNamesFromFolder(filepath, ".zip");
+// public static Object[] getZipFileNamesFromFolder(String filepath) {
+// return filterFileNamesFromFolder(filepath, ".zip");
+// }
+
+ public static List<String> getZipFileNamesFromFolder(String filepath) {
+ return filterFileNamesListFromFolder(filepath, ".zip");
}
public static int countFilesInZipFile(String[] artifactsArr, String reqExtension){
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java
index 19c2242550..44ff08938a 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/GeneralUIUtils.java
@@ -20,7 +20,6 @@
package org.openecomp.sdc.ci.tests.utilities;
-import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java
index 33b9f4a77e..eed4f765c5 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java
@@ -399,6 +399,7 @@ public class OnboardingUtils {
jObject.put("name", "xyz");
jObject.put("description", "new vendor license feature groups");
jObject.put("partNumber", "123abc456");
+ jObject.put("manufacturerReferenceNumber", "5");
jObject.put("addedLicenseKeyGroupsIds", Arrays.asList(licenseKeyGroupId).toArray());
jObject.put("addedEntitlementPoolsIds", Arrays.asList(entitlementPoolId).toArray());
@@ -514,7 +515,7 @@ public class OnboardingUtils {
return new Pair<RestResponse, Map<String, String>>(response, vspMetadta);
}
- public static RestResponse getVendorSoftwareProduct(Map vspObject, User user) throws Exception {
+/* public static RestResponse getVendorSoftwareProduct(Map vspObject, User user) throws Exception {
Config config = Utils.getConfig();
String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/" + vspObject.get("vspId"),
config.getCatalogBeHost(), config.getCatalogBePort());
@@ -527,7 +528,7 @@ public class OnboardingUtils {
RestResponse response = http.httpsSendGet(url, headersMap);
return response;
- }
+ }*/
public static RestResponse validateUpload(String vspid, User user) throws Exception {
Config config = Utils.getConfig();
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java
index e4c4840450..4035ef9243 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/verificator/ServiceVerificator.java
@@ -81,7 +81,7 @@ public class ServiceVerificator {
}
JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag);
int size = ((JSONArray) jsonResource.get("componentInstances")).size();
- assertTrue(size == numOfVFC);
+ assertTrue(size == numOfVFC, "Expected number of componenet instances is " + numOfVFC + ", but actual is " + size);
ExtentTestActions.log(Status.INFO, "The number of components on the canvas was verified.");
}
@@ -145,10 +145,10 @@ public class ServiceVerificator {
public static void verifyOpenTabTitle(DataTestIdEnum.CompositionScreenEnum currentTab) throws Exception{
List<String> expectedTitles = new ArrayList<String>();
for(String expectedTitle: currentTab.getTitle()){
- expectedTitles.add(expectedTitle);
+ expectedTitles.add(expectedTitle.toLowerCase());
}
for (WebElement actualTitle: CompositionPage.getOpenTabTitle()){
- int indexOfTitle = expectedTitles.indexOf(actualTitle.getText());
+ int indexOfTitle = expectedTitles.indexOf(actualTitle.getText().trim().toLowerCase());
assertTrue(indexOfTitle >= 0, "Wrong title");
expectedTitles.remove(indexOfTitle);
}
diff --git a/ui-ci/src/main/resources/ci/conf/attsdc.yaml b/ui-ci/src/main/resources/ci/conf/attsdc.yaml
index 1ab581cada..4dd7e75abd 100644
--- a/ui-ci/src/main/resources/ci/conf/attsdc.yaml
+++ b/ui-ci/src/main/resources/ci/conf/attsdc.yaml
@@ -1,7 +1,12 @@
outputFolder: target
reportName: index.html
-catalogBeHost: 127.0.0.1
-catalogFeHost: fehost
+#catalogBeHost: 127.0.0.1
+#Automate
+#catalogBeHost: 135.63.125.67
+#catalogFeHost: 135.63.125.63
+#IFT
+catalogBeHost: 135.21.143.248
+catalogFeHost: 135.21.125.96
esHost: eshost
disributionClientHost: disClient
catalogFePort: 8181
@@ -12,7 +17,9 @@ neoHost: neoHost
neoPort: 7474
neoDBusername: neo4j
neoDBpassword: 123456
-url: http://localhost:8285/sdc1
+#url: http://localhost:8285/sdc1
+#url: https://www.e-access.att.com/QA-AUTOMATE1/sdc1/portal
+url: https://www.e-access.att.com/AA-IFT-testing/sdc1/portal
remoteTestingMachineIP: 0.0.0.0
remoteTestingMachinePort: 5566
remoteTesting: false
diff --git a/ui-ci/src/main/resources/ci/scripts/copyToStorage.sh b/ui-ci/src/main/resources/ci/scripts/copyToStorage.sh
index 396c1aa0ac..a113c54e60 100644
--- a/ui-ci/src/main/resources/ci/scripts/copyToStorage.sh
+++ b/ui-ci/src/main/resources/ci/scripts/copyToStorage.sh
@@ -3,7 +3,7 @@
REPORT_NAME=$1
VERSION=$2
ENV=$3
-IP=$3
+
if [ -z "$REPORT_NAME" ]
then
@@ -20,6 +20,10 @@ if [ -z "$REPORT_NAME" ]
fi
+source conf/attInternal.info
+IP=$automationResutlsRepo
+PASS=$automationResutlsRepoPass
+
/usr/bin/expect << EOF
spawn ssh admin@${IP} mkdir -p -m 775 /home/admin/reports/${ENV}/${VERSION}/UI/
@@ -29,13 +33,13 @@ expect {
exp_continue
}
-re ".*sword.*" {
- exp_send "Aa123456\r"
+ exp_send ${PASS}\r
}
}
expect eof
-spawn scp -pr ExtentReport admin@{IP}:/home/admin/reports/${ENV}/${VERSION}/UI/${REPORT_NAME}/
+spawn scp -pr ExtentReport admin@${IP}:/home/admin/reports/${ENV}/${VERSION}/UI/${REPORT_NAME}/
expect {
-re ".*es.*o.*" {
@@ -43,7 +47,7 @@ expect {
exp_continue
}
-re ".*sword.*" {
- exp_send "Aa123456\r"
+ exp_send ${PASS}\r
}
}
diff --git a/ui-ci/src/main/resources/ci/testSuites/extendedSanity.xml b/ui-ci/src/main/resources/ci/testSuites/extendedSanity.xml
index da2bc98ebc..36993e382c 100644
--- a/ui-ci/src/main/resources/ci/testSuites/extendedSanity.xml
+++ b/ui-ci/src/main/resources/ci/testSuites/extendedSanity.xml
@@ -9,6 +9,8 @@
<class name="org.openecomp.sdc.ci.tests.execute.sanity.Onboard">
<methods>
<exclude name="onboardVNFTestSanity"/>
+ <exclude name="onboardVNFShotFlow"/>
+ <exclude name="onboardRandomVNFsTest"/>
</methods>
</class>
<class name="org.openecomp.sdc.ci.tests.execute.sanity.CatalogLeftPanelTest"/>
diff --git a/ui-ci/src/main/resources/ci/testSuites/onboardingVNFs.xml b/ui-ci/src/main/resources/ci/testSuites/onboardingVNFs.xml
index a49c8a751c..c55da4274c 100644
--- a/ui-ci/src/main/resources/ci/testSuites/onboardingVNFs.xml
+++ b/ui-ci/src/main/resources/ci/testSuites/onboardingVNFs.xml
@@ -1,16 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="uitests" configfailurepolicy="continue" parallel="methods" thread-count="2" data-provider-thread-count="2">
-<parameter name="makeDistribution" value="true"/>
- <test name="Onboarding">
+ <parameter name="makeDistribution" value="true"/>
+
+ <test name="uiSanity">
<classes>
<class name="org.openecomp.sdc.ci.tests.execute.sanity.Onboard">
<methods>
- <include name="onboardVNFTest"/>
+ <exclude name="onboardVNFTestSanity"/>
+ <exclude name="onboardVNFShotFlow"/>
+ <exclude name="onboardRandomVNFsTest"/>
</methods>
</class>
+
</classes>
</test> <!-- uitests -->
</suite> <!-- uisuite --> \ No newline at end of file
diff --git a/ui-ci/src/main/resources/ci/testSuites/onboardingVNFsShortFlow.xml b/ui-ci/src/main/resources/ci/testSuites/onboardingVNFsShortFlow.xml
new file mode 100644
index 0000000000..4a4628a9ed
--- /dev/null
+++ b/ui-ci/src/main/resources/ci/testSuites/onboardingVNFsShortFlow.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
+<suite name="uitests" configfailurepolicy="continue" parallel="methods" thread-count="2" data-provider-thread-count="2">
+ <parameter name="makeDistribution" value="true"/>
+
+ <test name="uiSanity">
+ <classes>
+
+ <class name="org.openecomp.sdc.ci.tests.execute.sanity.Onboard">
+ <methods>
+ <include name="onboardVNFShotFlow"/>
+ </methods>
+ </class>
+
+
+ </classes>
+ </test> <!-- uitests -->
+</suite> <!-- uisuite --> \ No newline at end of file