aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitignore1
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java50
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java46
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java2
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java7
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java6
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java99
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java22
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/HealthCheckAPI.java68
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java4
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java83
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java2
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetLeftPaletteTest.java193
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java75
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java6
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java8
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java10
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java12
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CommonRestUtils.java23
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java14
-rw-r--r--asdctool/pom.xml20
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1604/ServiceMigration.java5
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707ArtifactUuidFix.java4
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707Config.java5
-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/jsonmodel/ComponentMigration.java4
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/NodeTemplateMissingDataResolver.java129
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/main/MigrationMenu.java63
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/MigrationSpringConfig.java59
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/DBVersion.java95
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/MigrationException.java13
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/SdcMigrationTool.java62
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutionResult.java70
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutor.java15
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutorImpl.java47
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/task/Migration.java14
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/task/MigrationResult.java31
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/main/MigrationMenu.java100
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/MigrationResolver.java16
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/SpringBeansMigrationResolver.java45
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/service/SdcRepoService.java34
-rw-r--r--asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/ExampleMigration.java27
-rw-r--r--asdctool/src/main/resources/config/configuration.yaml1
-rw-r--r--asdctool/src/main/resources/config/logback.xml15
-rw-r--r--asdctool/src/main/resources/scripts/postMigration1707Fix.sh35
-rw-r--r--asdctool/src/main/resources/scripts/sdc-migration.sh36
-rw-r--r--asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/DummyMigrationFactory.java72
-rw-r--r--asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/core/DBVersionTest.java57
-rw-r--r--asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/core/SdcMigrationToolTest.java101
-rw-r--r--asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutorImplTest.java47
-rw-r--r--asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/resolver/SpringBeansMigrationResolverTest.java84
-rw-r--r--asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/scanner/ClassScanner.java81
-rw-r--r--asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/service/SdcRepoServiceTest.java55
-rw-r--r--asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/task/MigrationTasksTest.java56
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java125
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java189
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java50
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java58
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java56
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java31
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java361
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java98
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java1691
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java16
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java140
-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/impl/VFComponentInstanceBusinessLogic.java12
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/CertificationRequestTransition.java9
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java55
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java14
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java4
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java44
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java2
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java60
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java71
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java10
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java27
-rw-r--r--catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java13
-rw-r--r--catalog-be/src/main/resources/config/SDC.zipbin30057 -> 29275 bytes
-rw-r--r--catalog-be/src/main/resources/config/configuration.yaml23
-rw-r--r--catalog-be/src/main/resources/config/error-configuration.yaml518
-rw-r--r--catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml53
-rw-r--r--catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zipbin5277 -> 5408 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types.zipbin72549 -> 0 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_PNF/Generic_PNF.json21
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_PNF/Generic_PNF.yml11
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/Generic_PNF/Generic_PNF.zipbin0 -> 320 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.yml20
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.zipbin790 -> 780 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/multiFlavorVFC/multiFlavorVFC.json21
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/multiFlavorVFC/multiFlavorVFC.yml10
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/multiFlavorVFC/multiFlavorVFC.zipbin0 -> 714 bytes
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/vnfConfiguration/vnfConfiguration.json21
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/vnfConfiguration/vnfConfiguration.yml10
-rw-r--r--catalog-be/src/main/resources/import/tosca/heat-types/vnfConfiguration/vnfConfiguration.zipbin0 -> 759 bytes
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py7
-rw-r--r--catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py5
-rw-r--r--catalog-be/src/main/webapp/WEB-INF/web.xml1
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java18
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/ResourceImportManagerTest.java8
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java69
-rw-r--r--catalog-be/src/test/java/org/openecomp/sdc/be/components/lifecycle/LifecycleTestBase.java5
-rw-r--r--catalog-be/src/test/resources/config/catalog-be/configuration.yaml228
-rw-r--r--catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml535
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java9
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/MigrationTasksAccessor.java17
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/MigrationTasksDao.java73
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java23
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/MigrationTasksTableDescription.java81
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java15
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java4
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/MigrationTaskEntry.java92
-rw-r--r--catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java41
-rw-r--r--catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java3
-rw-r--r--catalog-model/pom.xml14
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java10
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java8
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/IPropertyInputCommon.java14
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/ImportCsarInfo.java73
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java55
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java12
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java18
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfo.java18
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java71
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java29
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java2
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java186
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java7
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementLifecycleOperation.java83
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java96
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java4041
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java46
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java7
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java9
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java7
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java1
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java1
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java1
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java3
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java4
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java4
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java4
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java10
-rw-r--r--catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java20
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java85
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java344
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java74
-rw-r--r--catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java114
-rw-r--r--catalog-ui/configurations/MenuReadMe.txt2
-rw-r--r--catalog-ui/configurations/dev.js14
-rw-r--r--catalog-ui/configurations/menu.js196
-rw-r--r--catalog-ui/configurations/mock.json14
-rw-r--r--catalog-ui/configurations/prod.js13
-rw-r--r--catalog-ui/pom.xml9
-rw-r--r--catalog-ui/src/app/app.ts25
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/common/style/component-instances-nodes-style.ts7
-rw-r--r--catalog-ui/src/app/directives/graphs-v2/palette/palette.directive.ts66
-rw-r--r--catalog-ui/src/app/directives/property-types/type-map/type-map-directive.html2
-rw-r--r--catalog-ui/src/app/directives/property-types/type-map/type-map-directive.ts5
-rw-r--r--catalog-ui/src/app/directives/structure-tree/structure-tree-directive.html2
-rw-r--r--catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.less4
-rw-r--r--catalog-ui/src/app/models.ts4
-rw-r--r--catalog-ui/src/app/models/app-config.ts12
-rw-r--r--catalog-ui/src/app/models/categories.ts1
-rw-r--r--catalog-ui/src/app/models/component-metadata.ts6
-rw-r--r--catalog-ui/src/app/models/components/component.ts7
-rw-r--r--catalog-ui/src/app/models/components/displayComponent.ts3
-rw-r--r--catalog-ui/src/app/models/components/product.ts125
-rw-r--r--catalog-ui/src/app/models/components/resource.ts5
-rw-r--r--catalog-ui/src/app/models/components/service.ts6
-rw-r--r--catalog-ui/src/app/models/componentsInstances/componentInstance.ts4
-rw-r--r--catalog-ui/src/app/models/componentsInstances/productInstance.ts33
-rw-r--r--catalog-ui/src/app/models/modal.ts16
-rw-r--r--catalog-ui/src/app/models/properties-inputs/input-fe-model.ts2
-rw-r--r--catalog-ui/src/app/models/properties-inputs/property-fe-model.ts10
-rw-r--r--catalog-ui/src/app/models/user.ts10
-rw-r--r--catalog-ui/src/app/modules/service-module.ts2
-rw-r--r--catalog-ui/src/app/modules/view-model-module.ts6
-rw-r--r--catalog-ui/src/app/ng2/app.component.ts4
-rw-r--r--catalog-ui/src/app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component.html3
-rw-r--r--catalog-ui/src/app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component.ts58
-rw-r--r--catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.html1
-rw-r--r--catalog-ui/src/app/ng2/components/inputs-table/inputs-table.component.ts10
-rw-r--r--catalog-ui/src/app/ng2/components/modal/modal.component.html16
-rw-r--r--catalog-ui/src/app/ng2/components/modal/modal.component.ts14
-rw-r--r--catalog-ui/src/app/ng2/components/modal/modal.module.ts19
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.html6
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.less9
-rw-r--r--catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.ts43
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.module.ts10
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.less3
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties-assignment.page.component.ts8
-rw-r--r--catalog-ui/src/app/ng2/pages/properties-assignment/properties.utils.ts5
-rw-r--r--catalog-ui/src/app/ng2/services/component-services/component.service.ts2
-rw-r--r--catalog-ui/src/app/ng2/services/http.interceptor.service.ts24
-rw-r--r--catalog-ui/src/app/ng2/services/modal.service.ts73
-rw-r--r--catalog-ui/src/app/services.ts1
-rw-r--r--catalog-ui/src/app/services/available-icons-service.ts17
-rw-r--r--catalog-ui/src/app/services/components/product-service.ts55
-rw-r--r--catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts45
-rw-r--r--catalog-ui/src/app/services/data-types-service.ts3
-rw-r--r--catalog-ui/src/app/services/entity-service.ts17
-rw-r--r--catalog-ui/src/app/utils/component-factory.ts20
-rw-r--r--catalog-ui/src/app/utils/component-instance-factory.ts10
-rw-r--r--catalog-ui/src/app/utils/constants.ts8
-rw-r--r--catalog-ui/src/app/utils/modals-handler.ts18
-rw-r--r--catalog-ui/src/app/view-models/catalog/catalog-view-model.ts8
-rw-r--r--catalog-ui/src/app/view-models/catalog/catalog.less22
-rw-r--r--catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts7
-rw-r--r--catalog-ui/src/app/view-models/dashboard/dashboard-view.html14
-rw-r--r--catalog-ui/src/app/view-models/dashboard/dashboard.less7
-rw-r--r--catalog-ui/src/app/view-models/dcae-app/dcae-app.less22
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts13
-rw-r--r--catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view.html2
-rw-r--r--catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.html18
-rw-r--r--catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.less33
-rw-r--r--catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.ts (renamed from catalog-ui/src/app/view-models/workspace/tabs/icons/icons-view-model.ts)88
-rw-r--r--catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor.less22
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.less5
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes.less2
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view-model.ts9
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html3
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html2
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts2
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view.html21
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details.less3
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less2
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/general/general-view-model.ts49
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html552
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/general/general.less80
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/icons/icons-view.html26
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/icons/icons.less65
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts.less2
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/inputs/inputs.less2
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model.ts129
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view.html40
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy.less130
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/properties/properties.less2
-rw-r--r--catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less5
-rw-r--r--catalog-ui/src/app/view-models/workspace/workspace-view-model.ts46
-rw-r--r--catalog-ui/src/app/view-models/workspace/workspace-view.html17
-rw-r--r--catalog-ui/src/app/view-models/workspace/workspace.less60
-rw-r--r--catalog-ui/src/assets/languages/en_US.json5
-rw-r--r--catalog-ui/src/assets/styles/app.less4
-rw-r--r--catalog-ui/src/assets/styles/images/resource-icons/vnfconfiguration.pngbin0 -> 2835 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/sprites/sprite-global.pngbin90334 -> 93182 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/sprites/sprite-product-icons.pngbin132122 -> 0 bytes
-rw-r--r--catalog-ui/src/assets/styles/images/sprites/sprite-resource-icons.pngbin474238 -> 476775 bytes
-rw-r--r--catalog-ui/src/assets/styles/mixins.less4
-rw-r--r--catalog-ui/src/assets/styles/modal.less7
-rw-r--r--catalog-ui/src/assets/styles/sprite-product-icons.less71
-rw-r--r--catalog-ui/src/assets/styles/sprite-resource-icons.less1
-rw-r--r--catalog-ui/src/assets/styles/sprite.less2
-rw-r--r--catalog-ui/src/assets/styles/variables-old.less2
-rw-r--r--catalog-ui/src/assets/styles/variables.less1
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java19
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java1
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java38
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java4
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java10
-rw-r--r--common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java30
-rw-r--r--common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ComponentMetadataDataDefinition.java19
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java21
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java38
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListDataDefinition.java8
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapDataDefinition.java12
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipInstDataDefinition.java16
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RequirementDataDefinition.java6
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java3
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java4
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java12
-rw-r--r--common-be/src/main/java/org/openecomp/sdc/be/datatypes/tosca/ToscaDataDefinition.java4
-rw-r--r--pom.xml2
-rw-r--r--sdc-os-chef/sdc-backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/BE-configuration.yaml.erb4
-rw-r--r--sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb5
-rw-r--r--sdc-os-chef/sdc-os-common/templates/default/BE-configuration.yaml.erb23
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java14
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java4
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/AndreyTest.java31
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java2
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java4
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java2
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java2
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaParameterConstants.java9
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java34
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java122
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java14
-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/rest/LifecycleRestUtils.java15
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java1
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java2
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java33
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java392
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetCSARofVF.java68
-rw-r--r--test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/VFCMTExternalAPI.java12
-rw-r--r--test-apis-ci/src/main/resources/ci/conf/attsdc.yaml2
-rw-r--r--test-apis-ci/src/test/resources/CI/error-configuration.yaml6
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MIBsArtifactsOnResourceInstance.java4
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java22
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Onboard.java41
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/OnboardViaApis.java32
-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/Vf.java4
-rw-r--r--ui-ci/src/main/java/org/openecomp/sdc/ci/tests/utilities/OnboardingUtils.java29
312 files changed, 10588 insertions, 6362 deletions
diff --git a/.gitignore b/.gitignore
index e9f00350d3..3ad4296d58 100644
--- a/.gitignore
+++ b/.gitignore
@@ -145,6 +145,7 @@ openecomp-ui/node/*
sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/SDC-*.zip
sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/files/default/sdctool.tar
sdc-os-chef/.idea/*
+node/*
# chef
.delivery
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java
index 9428a9b695..60c226136d 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java
@@ -91,6 +91,7 @@ public class ComponentInstanceBaseTest extends ComponentBaseTest {
protected ResourceReqDetails resourceDetailsVFC_02;
protected ResourceReqDetails resourceDetailsVF_01;
protected ResourceReqDetails resourceDetailsVF_02;
+ protected ResourceReqDetails resourceDetailsPNF_01;
protected ResourceReqDetails resourceDetailsCP_01;
protected ResourceReqDetails resourceDetailsCP_02;
protected ResourceReqDetails resourceDetailsVL_01;
@@ -119,6 +120,7 @@ public class ComponentInstanceBaseTest extends ComponentBaseTest {
resourceDetailsVFC_02 = ElementFactory.getDefaultResourceByType("ciVFC200", NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VFC.toString());
resourceDetailsVF_01 = ElementFactory.getDefaultResourceByType("ciVF100", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VF.toString());
resourceDetailsVF_02 = ElementFactory.getDefaultResourceByType("ciVF200", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VF.toString());
+ resourceDetailsPNF_01 = ElementFactory.getDefaultResourceByType("ciPNF100", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.PNF.toString());
resourceDetailsCP_01 = ElementFactory.getDefaultResourceByType("ciCP100", NormativeTypesEnum.PORT, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), ResourceTypeEnum.CP.toString());
resourceDetailsCP_02 = ElementFactory.getDefaultResourceByType("ciCP200", NormativeTypesEnum.PORT, ResourceCategoryEnum.GENERIC_DATABASE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.CP.toString());
resourceDetailsVL_01 = ElementFactory.getDefaultResourceByType("ciVL100", NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VL.toString());
@@ -338,9 +340,9 @@ public class ComponentInstanceBaseTest extends ComponentBaseTest {
Function<? super Entry<String, List<CapabilityDefinition>>, List<CapabilityDefinition>> capabilityDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new CapabilityDefinition(item)).collect(Collectors.toList()));
Map<String, List<CapabilityDefinition>> capCopy = resourceCapabilities.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), capabilityDefinitionMapper));
- setupContainerExpectedReqCap(uniqueId, name, resourceRequirements, resourceCapabilities);
+ setupContainerExpectedReqCap(uniqueId, name, originComponentId, resourceRequirements, resourceCapabilities);
if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE) && ((Resource) component).getResourceType() != ResourceTypeEnum.VF) {
- setupConstInstExpectedReqCap(uniqueId, name, reqCopy, capCopy);
+ setupConstInstExpectedReqCap(uniqueId, name, originComponentId, reqCopy, capCopy);
}
// adding entry for expected componentInstance
@@ -348,12 +350,15 @@ public class ComponentInstanceBaseTest extends ComponentBaseTest {
expectedContInstReqCap.put(uniqueId, compInstReqCapPair);
}
- private void setupContainerExpectedReqCap(String uniqueId, String name, Map<String, List<RequirementDefinition>> componentRequirements, Map<String, List<CapabilityDefinition>> componentCapabilities) {
+ private void setupContainerExpectedReqCap(String uniqueId, String name, String componentId, Map<String, List<RequirementDefinition>> componentRequirements, Map<String, List<CapabilityDefinition>> componentCapabilities) {
for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
List<RequirementDefinition> reqListToAdd = resReq.getValue();
for (RequirementDefinition requirementDefinition : reqListToAdd) {
requirementDefinition.setOwnerId(uniqueId);
requirementDefinition.setOwnerName(name);
+ requirementDefinition.addToPath(uniqueId);
+ requirementDefinition.setSource(componentId);
+ requirementDefinition.setLeftOccurrences(requirementDefinition.getMaxOccurrences());
}
List<RequirementDefinition> expectedReqList = expectedContainerRequirements.get(resReq.getKey());
if (expectedReqList == null) {
@@ -369,6 +374,9 @@ public class ComponentInstanceBaseTest extends ComponentBaseTest {
for (CapabilityDefinition capDefinition : capListToAdd) {
capDefinition.setOwnerId(uniqueId);
capDefinition.setOwnerName(name);
+ capDefinition.addToPath(uniqueId);
+ capDefinition.setSource(componentId);
+ capDefinition.setLeftOccurrences(capDefinition.getMaxOccurrences());
}
List<CapabilityDefinition> expectedCapList = expectedContainerCapabilities.get(resCap.getKey());
if (expectedCapList == null) {
@@ -380,12 +388,15 @@ public class ComponentInstanceBaseTest extends ComponentBaseTest {
}
}
- private void setupConstInstExpectedReqCap(String uniqueId, String name, Map<String, List<RequirementDefinition>> componentRequirements, Map<String, List<CapabilityDefinition>> componentCapabilities) {
+ private void setupConstInstExpectedReqCap(String uniqueId, String name, String componentId, Map<String, List<RequirementDefinition>> componentRequirements, Map<String, List<CapabilityDefinition>> componentCapabilities) {
for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
List<RequirementDefinition> reqListToAdd = resReq.getValue();
for (RequirementDefinition requirementDefinition : reqListToAdd) {
requirementDefinition.setOwnerId(uniqueId);
requirementDefinition.setOwnerName(name);
+ requirementDefinition.addToPath(uniqueId);
+ requirementDefinition.setSource(componentId);
+ requirementDefinition.setLeftOccurrences(requirementDefinition.getMaxOccurrences());
}
}
@@ -394,6 +405,8 @@ public class ComponentInstanceBaseTest extends ComponentBaseTest {
for (CapabilityDefinition capDefinition : capListToAdd) {
capDefinition.setOwnerId(uniqueId);
capDefinition.setOwnerName(name);
+ capDefinition.addToPath(uniqueId);
+ capDefinition.setSource(componentId);
}
}
}
@@ -570,6 +583,31 @@ public class ComponentInstanceBaseTest extends ComponentBaseTest {
return component;
}
+ protected Component getComponentAndValidateRIsOnly(ComponentReqDetails componentDetails, int numberOfRIs, int numberOfRelations) throws IOException, Exception {
+
+ RestResponse getResponse = null;
+ Component component = null;
+ if (componentDetails instanceof ResourceReqDetails) {
+ getResponse = ResourceRestUtils.getResource(sdncAdminDetails, componentDetails.getUniqueId());
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class);
+ } else if (componentDetails instanceof ServiceReqDetails) {
+ getResponse = ServiceRestUtils.getService((ServiceReqDetails) componentDetails, sdncAdminDetails);
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class);
+ } else if (componentDetails instanceof ProductReqDetails) {
+ getResponse = ProductRestUtils.getProduct(componentDetails.getUniqueId(), sdncAdminDetails.getUserId());
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Product.class);
+ } else {
+ Assert.fail("Unsupported type of componentDetails - " + componentDetails.getClass().getSimpleName());
+ }
+ ResourceRestUtils.checkSuccess(getResponse);
+ int numberOfActualRIs = component.getComponentInstances() != null ? component.getComponentInstances().size() : 0;
+ int numberOfActualRelations = component.getComponentInstancesRelations() != null ? component.getComponentInstancesRelations().size() : 0;
+ assertEquals("Check number of RIs meet the expected number", numberOfRIs, numberOfActualRIs);
+ assertEquals("Check number of RI relations meet the expected number", numberOfRelations, numberOfActualRelations);
+
+ return component;
+ }
+
protected void getComponentAndValidateRIsAfterChangeLifecycleState(String oldComponentUniqueIdToReplace, ComponentReqDetails componentDetails, int numOfRIs, int numOfRelations) throws IOException, Exception {
updateExpectedReqCapAfterChangeLifecycleState(oldComponentUniqueIdToReplace, componentDetails.getUniqueId());
getComponentAndValidateRIs(componentDetails, numOfRIs, numOfRelations);
@@ -612,6 +650,10 @@ public class ComponentInstanceBaseTest extends ComponentBaseTest {
ResourceRestUtils.checkCreateResponse(createVfResponse);
}
+ protected void createPNF(ResourceReqDetails resourceDetails) throws Exception {
+ createVF(resourceDetails, sdncDesignerDetails);
+ }
+
protected void createService(ServiceReqDetails serviceDetails) throws Exception {
createService(serviceDetails, sdncDesignerDetails);
}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
index 0e1c0e4da1..3e4411b06e 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
@@ -45,6 +45,8 @@ public interface Urls {
final String GET_SERVICE_lATEST_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/services/latestversion/notabstract";
+ final String GET_RESOURCE_METADATA_lATEST_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/resources/latestversion/notabstract/metadata";
+
// Get resource artifact list:
// http://172.20.43.124:8080/sdc2/rest/v1/catalog/resources/alien.nodes.Apache/2.0.0-SNAPSHOT/artifacts
final String GET_RESOURCE_ARTIFACTS_LIST = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/artifacts";
@@ -186,35 +188,35 @@ public interface Urls {
// ***********************************External API's
// (AssetData)****************************************
- final String DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/artifacts/%s";
- final String DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
+ final String DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_ASSET = "http://%s:%s/sdc/v1/catalog/%s/%s/artifacts/%s";
+ final String DELETE_EXTRNAL_API_DELETE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
- final String POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/artifacts/%s";
- final String POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
+ final String POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_ASSET = "http://%s:%s/sdc/v1/catalog/%s/%s/artifacts/%s";
+ final String POST_EXTERNAL_API_UPDATE_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
- final String POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/artifacts";
- final String POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts";
+ final String POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_ASSET = "http://%s:%s/sdc/v1/catalog/%s/%s/artifacts";
+ final String POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_COMPONENTINSTANCE_ON_ASSET = "http://%s:%s/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts";
- final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/resources/%s/artifacts/%s";
- final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/services/%s/artifacts/%s";
+ final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_ASSET = "http://%s:%s/sdc/v1/catalog/resources/%s/artifacts/%s";
+ final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_ASSET = "http://%s:%s/sdc/v1/catalog/services/%s/artifacts/%s";
- final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_COMPONENT_INSTANCE = "http://%s:%s/asdc/v1/catalog/resources/%s/resourceInstances/%s/artifacts/%s";
- final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_COMPONENT_INSTANCE = "http://%s:%s/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
+ final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_COMPONENT_INSTANCE = "http://%s:%s/sdc/v1/catalog/resources/%s/resourceInstances/%s/artifacts/%s";
+ final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_COMPONENT_INSTANCE = "http://%s:%s/sdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
- final String GET_ASSET_LIST = "http://%s:%s/asdc/v1/catalog/%s";
- final String GET_FILTERED_ASSET_LIST = "http://%s:%s/asdc/v1/catalog/%s?%s";
- final String GET_TOSCA_MODEL = "http://%s:%s/asdc/v1/catalog/%s/%s/toscaModel";
- // https://{serverRoot}/asdc/v1/catalog/{assetType}/{uuid}/metadata, where
+ final String GET_ASSET_LIST = "http://%s:%s/sdc/v1/catalog/%s";
+ final String GET_FILTERED_ASSET_LIST = "http://%s:%s/sdc/v1/catalog/%s?%s";
+ final String GET_TOSCA_MODEL = "http://%s:%s/sdc/v1/catalog/%s/%s/toscaModel";
+ // https://{serverRoot}/sdc/v1/catalog/{assetType}/{uuid}/metadata, where
// assetType in {resources, services}
- final String GET_ASSET_METADATA = "http://%s:%s/asdc/v1/catalog/%s/%s/metadata";
+ final String GET_ASSET_METADATA = "http://%s:%s/sdc/v1/catalog/%s/%s/metadata";
final String POST_AUTHORIZATION = "http://%s:%s/sdc2/rest/v1/consumers";
- final String GET_DOWNLOAD_SERVICE_RI_ARTIFACT = "http://%s:%s/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
- final String GET_DOWNLOAD_SERVICE_ARTIFACT = "http://%s:%s/asdc/v1/catalog/services/%s/artifacts/%s";
+ final String GET_DOWNLOAD_SERVICE_RI_ARTIFACT = "http://%s:%s/sdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
+ final String GET_DOWNLOAD_SERVICE_ARTIFACT = "http://%s:%s/sdc/v1/catalog/services/%s/artifacts/%s";
- final String POST_EXTERNAL_API_CREATE_RESOURCE = "http://%s:%s/asdc/v1/catalog/resources";
+ final String POST_EXTERNAL_API_CREATE_RESOURCE = "http://%s:%s/sdc/v1/catalog/resources";
- final String CHANGE_RESOURCE_LIFECYCLE_STATE_EXTERNAL_API = "http://%s:%s/asdc/v1/catalog/resources/%s/lifecycleState/%s";
- final String CHANGE_SERVICE_LIFECYCLE_STATE_EXTERNAL_API = "http://%s:%s/asdc/v1/catalog/services/%s/lifecycleState/%s";
+ final String CHANGE_RESOURCE_LIFECYCLE_STATE_EXTERNAL_API = "http://%s:%s/sdc/v1/catalog/resources/%s/lifecycleState/%s";
+ final String CHANGE_SERVICE_LIFECYCLE_STATE_EXTERNAL_API = "http://%s:%s/sdc/v1/catalog/services/%s/lifecycleState/%s";
// *****************************************************************************************************
@@ -238,8 +240,8 @@ public interface Urls {
final String DISTRIB_DOWNLOAD_SERVICE_ARTIFACT = "/sdc2/rest/v1/catalog/services/%s/%s/artifacts/%s";
// "/sdc2/v1/services/<serviceName>/<0.1>/resources/{resourceName}/{resourceVersion}/artifacts/<opeartion_name>_aaa.hh"
final String DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT = "/sdc2/rest/v1/catalog/services/%s/%s/resources/%s/%s/artifacts/%s";
- final String DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL = "/asdc/v1/catalog/services/%s/%s/artifacts/%s";
- final String DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL = "/asdc/v1/catalog/services/%s/%s/resources/%s/%s/artifacts/%s";
+ final String DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL = "/sdc/v1/catalog/services/%s/%s/artifacts/%s";
+ final String DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL = "/sdc/v1/catalog/services/%s/%s/resources/%s/%s/artifacts/%s";
final String DOWNLOAD_SERVICE_ARTIFACT_FULL_URL = "http://%s:%s%s";
final String DOWNLOAD_RESOURCE_ARTIFACT_FULL_URL = "http://%s:%s%s";
// **********************************************************************************
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java
index 8456e5b35b..d8bd80115e 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java
@@ -29,6 +29,7 @@ public class ResourceReqDetails extends ComponentReqDetails {
List<String> derivedFrom;
String vendorName;
String vendorRelease;
+ String resourceVendorModelNumber;
// Unsettable/unupdatable fields
@@ -55,6 +56,7 @@ public class ResourceReqDetails extends ComponentReqDetails {
this.derivedFrom = resource.getDerivedFrom();
this.vendorName = resource.getVendorName();
this.vendorRelease = resource.getVendorRelease();
+ this.resourceVendorModelNumber = resource.getResourceVendorModelNumber();
this.contactId = resource.getContactId();
this.icon = resource.getIcon();
this.toscaResourceName = resource.getToscaResourceName();
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java
index e33183ca94..022caecf41 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java
@@ -26,6 +26,9 @@ import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.category.CategoryDefinition;
public class ServiceReqDetails extends ComponentReqDetails {
+
+ String serviceType;
+ String serviceRole;
public ServiceReqDetails(String serviceName, String category, ArrayList<String> tags, String description,
String contactId, String icon) {
@@ -35,6 +38,8 @@ public class ServiceReqDetails extends ComponentReqDetails {
this.description = description;
this.contactId = contactId;
this.icon = icon;
+ this.serviceType = "";
+ this.serviceRole = "";
projectCode = "12345";
CategoryDefinition categoryDefinition = new CategoryDefinition();
categoryDefinition.setName(category);
@@ -56,6 +61,8 @@ public class ServiceReqDetails extends ComponentReqDetails {
this.uniqueId = service.getUniqueId();
this.UUID = service.getUUID();
this.version = service.getVersion();
+ this.serviceType = service.getServiceType();
+ this.serviceRole = service.getServiceRole();
}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java
index 5ec4a86977..e4c89bee94 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java
@@ -178,7 +178,7 @@ public class DownloadComponentArt extends ComponentBaseTest {
expectedResourceAuditJavaObject.setDesc("OK");
expectedResourceAuditJavaObject.setCONSUMER_ID("ci");
- String resource_url = String.format("/asdc/v1/catalog/resources/%s/artifacts/%s", resourceUUID, artifactUUID);
+ String resource_url = String.format("/sdc/v1/catalog/resources/%s/artifacts/%s", resourceUUID, artifactUUID);
expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false);
@@ -250,7 +250,7 @@ public class DownloadComponentArt extends ComponentBaseTest {
expectedResourceAuditJavaObject.setDesc("OK");
expectedResourceAuditJavaObject.setCONSUMER_ID("ci");
- String resource_url = String.format("/asdc/v1/catalog/services/%s/artifacts/%s", resourceUUID, artifactUUID);
+ String resource_url = String.format("/sdc/v1/catalog/services/%s/artifacts/%s", resourceUUID, artifactUUID);
expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false);
@@ -313,7 +313,7 @@ public class DownloadComponentArt extends ComponentBaseTest {
expectedResourceAuditJavaObject.setDesc("OK");
expectedResourceAuditJavaObject.setCONSUMER_ID("ci");
- String resource_url = String.format("/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s", resourceUUID, componentNormalizedName, artifactUUID);
+ String resource_url = String.format("/sdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s", resourceUUID, componentNormalizedName, artifactUUID);
expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false);
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java
index 86641eb2c7..44b781f065 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java
@@ -20,26 +20,21 @@
package org.openecomp.sdc.ci.tests.execute.category;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
+import java.util.*;
-import org.apache.log4j.lf5.util.ResourceUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.junit.Rule;
import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.config.Config;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
-import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.*;
import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
@@ -49,9 +44,8 @@ import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
import org.testng.AssertJUnit;
-import org.testng.annotations.AfterMethod;
+import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -62,6 +56,7 @@ public class CatalogDataApiTest extends ComponentBaseTest {
protected Config config = Config.instance();
protected String contentTypeHeaderData = "application/json";
protected String acceptHeaderDate = "application/json";
+ protected boolean isInitialized = false;
@Rule
public static TestName name = new TestName();
@@ -79,28 +74,36 @@ public class CatalogDataApiTest extends ComponentBaseTest {
@BeforeMethod
public void setUp() throws Exception {
+ if (isInitialized)
+ return;
user = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
resourceDetails1 = buildResourceDetails(user, "TestResource1");
+ resourceDetails1.setResourceType(ResourceTypeEnum.VFCMT.name());
resourceDetails2 = buildResourceDetails(user, "TestResource2");
svcDetails1 = buildServiceDetails("TestService1");
+ // VFCMT
res1 = createResource(user, resourceDetails1);
AssertJUnit.assertEquals("create resorce failed", 201, res1.getErrorCode().intValue());
resourceDetails1.setUniqueId(ResponseParser.getUniqueIdFromResponse(res1));
+
resourceDetails2.setVersion(ResponseParser.getVersionFromResponse(res1));
+ // VFC
res2 = createResource(user, resourceDetails2);
AssertJUnit.assertEquals("create resorce failed", 201, res2.getErrorCode().intValue());
resourceDetails2.setUniqueId(ResponseParser.getUniqueIdFromResponse(res2));
resourceDetails2.setVersion(ResponseParser.getVersionFromResponse(res2));
+ // SERVICE
svc1 = createService(user, svcDetails1);
AssertJUnit.assertEquals("create resorce failed", 201, svc1.getErrorCode().intValue());
svcDetails1.setUniqueId(ResponseParser.convertServiceResponseToJavaObject(svc1.getResponse()).getUniqueId());
svcDetails1.setVersion(ResponseParser.convertServiceResponseToJavaObject(svc1.getResponse()).getVersion());
+ isInitialized = true;
}
- @AfterMethod
+ @AfterClass
public void tearDown() throws Exception {
deleteResource(resourceDetails1.getUniqueId(), user.getUserId());
deleteResource(resourceDetails2.getUniqueId(), user.getUserId());
@@ -131,6 +134,66 @@ public class CatalogDataApiTest extends ComponentBaseTest {
}
+ @Test
+ public void getCatalogDataNoVFCMT() throws Exception {
+
+ List<String> excludeTyps = Arrays.asList(OriginTypeEnum.VFCMT.name());
+ RestResponse res = CatalogRestUtils.getCatalog(user.getUserId(), excludeTyps);
+ String json = res.getResponse();
+ JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
+ JSONArray resources = (JSONArray) jsonResp.get("resources");
+ JSONArray services = (JSONArray) jsonResp.get("services");
+
+ // Verify all the expected resources received except of resource1 which is VFCMT
+ AssertJUnit.assertFalse("check resource1 is in response",
+ isComponentInArray(resourceDetails1.getUniqueId(), resources));
+ AssertJUnit.assertTrue("check resource2 is in response",
+ isComponentInArray(resourceDetails2.getUniqueId(), resources));
+ AssertJUnit.assertTrue("check service1 is in response",
+ isComponentInArray(svcDetails1.getUniqueId(), services));
+
+ }
+
+ @Test
+ public void getCatalogDataNoVFCandVFCMT() throws Exception {
+
+ List<String> excludeTyps = Arrays.asList(OriginTypeEnum.VFCMT.name(), OriginTypeEnum.VFC.name());
+ RestResponse res = CatalogRestUtils.getCatalog(user.getUserId(), excludeTyps);
+ String json = res.getResponse();
+ JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
+ JSONArray resources = (JSONArray) jsonResp.get("resources");
+ JSONArray services = (JSONArray) jsonResp.get("services");
+
+ // Verify all the expected resources received except of VFCMT & VFC
+ AssertJUnit.assertFalse("check resource1 is in response",
+ isComponentInArray(resourceDetails1.getUniqueId(), resources));
+ AssertJUnit.assertFalse("check resource2 is in response",
+ isComponentInArray(resourceDetails2.getUniqueId(), resources));
+ AssertJUnit.assertTrue("check service1 is in response",
+ isComponentInArray(svcDetails1.getUniqueId(), services));
+
+ }
+
+ @Test
+ public void getCatalogDataNoServiceAndVFC() throws Exception {
+
+ List<String> excludeTyps = Arrays.asList(OriginTypeEnum.SERVICE.name(), OriginTypeEnum.VFC.name());
+ RestResponse res = CatalogRestUtils.getCatalog(user.getUserId(), excludeTyps);
+ String json = res.getResponse();
+ JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
+ JSONArray resources = (JSONArray) jsonResp.get("resources");
+ JSONArray services = (JSONArray) jsonResp.get("services");
+
+ // Verify all the expected resources received except of VFC & SERVICE
+ AssertJUnit.assertTrue("check resource1 is in response",
+ isComponentInArray(resourceDetails1.getUniqueId(), resources));
+ AssertJUnit.assertFalse("check resource2 is in response",
+ isComponentInArray(resourceDetails2.getUniqueId(), resources));
+ AssertJUnit.assertFalse("check service1 is in response",
+ isComponentInArray(svcDetails1.getUniqueId(), services));
+
+ }
+
protected void deleteResource(String resourceUniqueId, String httpCspUserId) throws Exception {
RestResponse deleteResourceResponse = ResourceRestUtils.deleteResource(resourceUniqueId, httpCspUserId);
@@ -171,6 +234,7 @@ public class CatalogDataApiTest extends ComponentBaseTest {
protected RestResponse createService(User user, ServiceReqDetails svcDetails) throws Exception {
+ deleteService(svcDetails1.getUniqueId(), user);
Config config = Utils.getConfig();
Map<String, String> headersMap = getHeadersMap(user);
@@ -189,7 +253,7 @@ public class CatalogDataApiTest extends ComponentBaseTest {
Map<String, String> headersMap = new HashMap<String, String>();
headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
- headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
+ headersMap.put("USER_ID", user.getUserId());
return headersMap;
}
@@ -210,15 +274,8 @@ public class CatalogDataApiTest extends ComponentBaseTest {
}
public RestResponse deleteService(String serviceId, User user) throws Exception {
- HttpRequest httpRequest = new HttpRequest();
- String url = String.format(Urls.DELETE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(),
- serviceId);
-
- Map<String, String> headersMap = getHeadersMap(user);
- RestResponse res = httpRequest.httpSendDelete(url, headersMap);
- // System.out.println("Delete service was finished with response:
- // "+res.getErrorCode());
- return res;
+ RestResponse deleteServiceResponse = ResourceRestUtils.deleteResource(serviceId, user.getUserId());
+ return deleteServiceResponse;
}
public class NewObject {
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java
index 7e8d5cf8cc..4a4e5a4529 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java
@@ -435,7 +435,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts");
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts");
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);
return restResponse;
@@ -584,13 +584,13 @@ public class CRUDExternalAPI extends ComponentBaseTest {
//
// if(componentTypeEnum == ComponentTypeEnum.RESOURCE_INSTANCE) {
// expectedResourceAuditJavaObject.setResourceName(resourceDetails.getComponentInstances().get(0).getName());
-// String resource_url = String.format("/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s", resourceDetails.getUUID(), resourceDetails.getComponentInstances().get(0).getNormalizedName(), artifactDefinition.getArtifactUUID());
+// String resource_url = String.format("/sdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s", resourceDetails.getUUID(), resourceDetails.getComponentInstances().get(0).getNormalizedName(), artifactDefinition.getArtifactUUID());
// expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
//
// AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false);
// } else {
// expectedResourceAuditJavaObject.setResourceName(resourceDetails.getName());
-// String resource_url = String.format("/asdc/v1/catalog/services/%s/artifacts/%s", resourceDetails.getUUID(), artifactDefinition.getArtifactUUID());
+// String resource_url = String.format("/sdc/v1/catalog/services/%s/artifacts/%s", resourceDetails.getUUID(), artifactDefinition.getArtifactUUID());
// expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
// }
//
@@ -1092,7 +1092,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentResourceInstanceDetails != null) {
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
} else {
expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
@@ -1148,7 +1148,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentResourceInstanceDetails != null) {
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
} else {
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
@@ -2354,7 +2354,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentInstance != null) {
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
} else {
expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL() + "/" + artifactUUID);
@@ -2511,7 +2511,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
// expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body);
return restResponse;
@@ -3151,7 +3151,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentInstance != null) {
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
} else {
expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL() + "/" + artifactUUID);
@@ -3248,7 +3248,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
// expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), body);
return restResponse;
@@ -3314,13 +3314,13 @@ public class CRUDExternalAPI extends ComponentBaseTest {
//
// if(componentTypeEnum == ComponentTypeEnum.RESOURCE_INSTANCE) {
// expectedResourceAuditJavaObject.setResourceName(resourceDetails.getComponentInstances().get(0).getName());
-// String resource_url = String.format("/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s", resourceDetails.getUUID(), resourceDetails.getComponentInstances().get(0).getNormalizedName(), artifactDefinition.getArtifactUUID());
+// String resource_url = String.format("/sdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s", resourceDetails.getUUID(), resourceDetails.getComponentInstances().get(0).getNormalizedName(), artifactDefinition.getArtifactUUID());
// expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
//
// AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null, false);
// } else {
// expectedResourceAuditJavaObject.setResourceName(resourceDetails.getName());
-// String resource_url = String.format("/asdc/v1/catalog/services/%s/artifacts/%s", resourceDetails.getUUID(), artifactDefinition.getArtifactUUID());
+// String resource_url = String.format("/sdc/v1/catalog/services/%s/artifacts/%s", resourceDetails.getUUID(), artifactDefinition.getArtifactUUID());
// expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
// }
//
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/HealthCheckAPI.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/HealthCheckAPI.java
new file mode 100644
index 0000000000..cb36619f80
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/HealthCheckAPI.java
@@ -0,0 +1,68 @@
+package org.openecomp.sdc.ci.tests.execute.devCI;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.CommonRestUtils;
+import org.openecomp.sdc.common.api.HealthCheckInfo;
+import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckComponent;
+import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
+import org.openecomp.sdc.common.api.HealthCheckWrapper;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+public class HealthCheckAPI extends ComponentBaseTest {
+
+ @Rule
+ public static TestName name = new TestName();
+
+ private static final int STATUS_CODE_GET_SUCCESS = 200;
+
+ public HealthCheckAPI() {
+ super(name, HealthCheckAPI.class.getName());
+ }
+
+ @Test
+ public void checkAmdocsHealthCheckAPI() throws Exception {
+ RestResponse healthCheckInfoResponse = CommonRestUtils.getHealthCheck();
+ BaseRestUtils.checkSuccess(healthCheckInfoResponse);
+
+ Gson gson = new Gson();
+ HealthCheckWrapper healthCheckInfo = gson.fromJson(healthCheckInfoResponse.getResponse(), HealthCheckWrapper.class);
+ assertNotNull("Health check not contains components info", healthCheckInfo.getComponentsInfo());
+ HealthCheckInfo amdocsHC = healthCheckInfo.getComponentsInfo().stream().filter(x -> x.getHealthCheckComponent() == HealthCheckInfo.HealthCheckComponent.ON_BOARDING).findFirst().orElse(null);
+ assertNotNull("Amdocs health check not exists in Health Check info", amdocsHC);
+ assertEquals("Amdocs health check is down", HealthCheckInfo.HealthCheckStatus.UP, amdocsHC.getHealthCheckStatus());
+ assertNotNull("Amdocs additionalInfo not exists in health check", amdocsHC.getComponentsInfo());
+ Map<HealthCheckComponent, HealthCheckStatus> amdocsHCComponents = amdocsHC.getComponentsInfo().stream().collect(Collectors.toMap(HealthCheckInfo::getHealthCheckComponent, HealthCheckInfo::getHealthCheckStatus));
+ assertNotNull(amdocsHCComponents);
+ assertTrue("Amdocs health check ZU component is down or not exists", amdocsHCComponents.get(HealthCheckComponent.ZU) != null && amdocsHCComponents.get(HealthCheckComponent.ZU).equals(HealthCheckStatus.UP));
+ assertTrue("Amdocs health check BE component is down or not exists", amdocsHCComponents.get(HealthCheckComponent.BE) != null && amdocsHCComponents.get(HealthCheckComponent.BE).equals(HealthCheckStatus.UP));
+ assertTrue("Amdocs health check CAS component is down or not exists", amdocsHCComponents.get(HealthCheckComponent.CAS) != null && amdocsHCComponents.get(HealthCheckComponent.CAS).equals(HealthCheckStatus.UP));
+ }
+
+ @Test
+ public void checkCassandraHealthCheck() throws Exception {
+ RestResponse healthCheckInfoResponse = CommonRestUtils.getHealthCheck();
+ BaseRestUtils.checkSuccess(healthCheckInfoResponse);
+
+ Gson gson = new Gson();
+ HealthCheckWrapper healthCheckInfo = gson.fromJson(healthCheckInfoResponse.getResponse(), HealthCheckWrapper.class);
+ assertNotNull("Health check not contains components info", healthCheckInfo.getComponentsInfo());
+ HealthCheckInfo cassandraHC = healthCheckInfo.getComponentsInfo().stream().filter(x -> x.getHealthCheckComponent() == HealthCheckInfo.HealthCheckComponent.CASSANDRA).findFirst().orElse(null);
+ assertNotNull("Cassandra health check not exists in Health Check info", cassandraHC);
+ assertEquals("Cassandra health check is down", HealthCheckInfo.HealthCheckStatus.UP, cassandraHC.getHealthCheckStatus());
+ }
+
+} \ No newline at end of file
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java
index bc114e22c5..c52ee470cf 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java
@@ -163,13 +163,13 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceDetails.getVersion(),
ValidationUtils.convertToSystemName(resourceDetails.getName()), resourceDetails.getVersion(),
ValidationUtils.normalizeFileName(deploymentArtifact.getArtifactName()));
- expectedDownloadResourceUrl = expectedDownloadResourceUrl.substring("/asdc/".length(),
+ expectedDownloadResourceUrl = expectedDownloadResourceUrl.substring("/sdc/".length(),
expectedDownloadResourceUrl.length());
expectedDownloadServiceUrl = String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL,
ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceDetails.getVersion(),
ValidationUtils.normalizeFileName(deploymentArtifact.getArtifactName()));
- expectedDownloadServiceUrl = expectedDownloadServiceUrl.substring("/asdc/".length(),
+ expectedDownloadServiceUrl = expectedDownloadServiceUrl.substring("/sdc/".length(),
expectedDownloadServiceUrl.length());
sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java
index 16d3fcb092..a58ec18840 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java
@@ -43,6 +43,8 @@ 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.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
@@ -51,7 +53,9 @@ 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.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
import org.openecomp.sdc.common.util.YamlToObjectConverter;
import org.testng.annotations.Test;
import org.yaml.snakeyaml.Yaml;
@@ -94,13 +98,18 @@ public class CsarUtilsTest extends ComponentBaseTest {
public void createResourceCsarBasicTest() throws Exception {
Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
resourceVF = (Resource) AtomicOperationUtils
.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
- User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, resourceVF);
csarBasicValidation(resourceVF, downloadCSAR);
+
+ validateVFCsar(resourceVF, downloadCSAR, 1, 0, 0, 0, 0, 0, 0);
+
+
}
@Test(enabled = true)
@@ -138,6 +147,7 @@ public class CsarUtilsTest extends ComponentBaseTest {
Resource resourceVF1 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+
AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, resourceVF1, UserRoleEnum.DESIGNER, true, true);
AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_ARTIFACT, resourceVF1, UserRoleEnum.DESIGNER, true, true);
@@ -157,7 +167,7 @@ public class CsarUtilsTest extends ComponentBaseTest {
public void createResourceCsarInclInformationalArtTest() throws Exception {
Resource resourceVF1 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
-
+
AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, resourceVF1, UserRoleEnum.DESIGNER, false, true);
AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceVF1, UserRoleEnum.DESIGNER, false, true);
@@ -173,6 +183,59 @@ public class CsarUtilsTest extends ComponentBaseTest {
validateVFCsar(resourceVF1, downloadCSAR, 1, 0, 0, 0, 1, 1, 0);
}
+ @Test(enabled = true)
+ public void createServiceCsarNotMandatoryMetadataFieldsTest() throws Exception {
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ service.setServiceType("serviceTypeTest");
+ service.setServiceRole("serviceRoleTest");
+ ServiceRestUtils.updateService(new ServiceReqDetails(service), sdncModifierDetails);
+
+ Resource resourceVF1 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ Resource resourceVF2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+
+ resourceVF1 = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ resourceVF2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF1, service, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF2, service, UserRoleEnum.DESIGNER, true);
+
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, service);
+
+ csarBasicValidation(service, downloadCSAR);
+
+ validateServiceCsar(resourceVF1, resourceVF2, service, downloadCSAR, 3, 3, 0, 0);
+ }
+
+ @Test(enabled = true)
+ public void createResourceCsarNotMandatoryMetadataFieldsTest() throws Exception {
+
+ Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ resourceVF.setResourceVendorModelNumber("modelNumberTest");
+ ResourceRestUtils.updateResourceMetadata(new ResourceReqDetails(resourceVF), sdncModifierDetails, resourceVF.getUniqueId());
+
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, resourceVF);
+
+ csarBasicValidation(resourceVF, downloadCSAR);
+
+ validateVFCsar(resourceVF, downloadCSAR, 1, 0, 0, 0, 0, 0, 0);
+
+
+ }
+
+
private void csarBasicValidation(Component mainComponent, byte[] downloadCSAR) {
try (ByteArrayInputStream ins = new ByteArrayInputStream(downloadCSAR);
ZipInputStream zip = new ZipInputStream(ins);) {
@@ -234,11 +297,12 @@ public class CsarUtilsTest extends ComponentBaseTest {
while ((len = zip.read(buffer)) > 0) {
sb.append(new String(buffer, 0, len));
}
- assertTrue(nextEntry.getName().equals("csar.meta"));
-
+ assertTrue(nextEntry.getName().equals("csar.meta"));
readNextEntry(sb, len, buffer, zip);
nextEntry = zip.getNextEntry();
assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta"));
+ readNextEntry(sb, len, buffer, zip);
+
YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
@@ -483,15 +547,24 @@ public class CsarUtilsTest extends ComponentBaseTest {
String UUID = (String) metadata.get("UUID");
assertNotNull(UUID);
- assertEquals("Validate component invariantUUID", component.getUUID(), UUID);
+ assertEquals("Validate component UUID", component.getUUID(), UUID);
String type = (String) metadata.get("type");
assertNotNull(type);
if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
assertEquals("Validate component type", component.getComponentType().getValue(), type);
+ String serviceType = (String) metadata.get("serviceType");
+ assertNotNull(serviceType);
+ assertEquals("Validate service type", ((Service )component).getServiceType(), serviceType);
+ String serviceRole = (String) metadata.get("serviceRole");
+ assertNotNull(serviceRole);
+ assertEquals("Validate service role", ((Service )component).getServiceRole(), serviceRole);
} else {
assertEquals("Validate component type", ((Resource) component).getResourceType(),
ResourceTypeEnum.valueOf(type));
+ String resourceVendorModelNumber = (String) metadata.get("resourceVendorModelNumber");
+ assertNotNull(resourceVendorModelNumber);
+ assertEquals("Validate resource vendor model number", ((Resource )component).getResourceVendorModelNumber(), resourceVendorModelNumber);
}
}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java
index 6bf0786a4b..5f0cbaf1c7 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java
@@ -156,7 +156,7 @@ public class ExportToscaTest extends ComponentBaseTest {
assertNotNull(vfModulesInRes);
assertNotNull(groups);
- assertEquals("Validate count of vf module instanses", vfModulesInRes.size(), groups.size());
+ assertEquals("Validate count of vf module instances", vfModulesInRes.size(), groups.size());
vfModulesInRes.forEach(modInRes -> {
validateVfModuleVsInstance(normalizedName, groups, modInRes);
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetLeftPaletteTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetLeftPaletteTest.java
new file mode 100644
index 0000000000..4ad008633a
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetLeftPaletteTest.java
@@ -0,0 +1,193 @@
+package org.openecomp.sdc.ci.tests.execute.resource;
+
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.JSONValue;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.Test;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import static org.testng.AssertJUnit.assertTrue;
+
+/**
+ * Created by chaya on 6/15/2017.
+ */
+public class GetLeftPaletteTest extends ComponentBaseTest {
+
+ private static Logger logger = LoggerFactory.getLogger(GetLeftPaletteTest.class.getName());
+ protected User designerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ protected ResourceReqDetails vlResourceDetails;
+ protected ResourceReqDetails cpResourceDetails;
+ protected ResourceReqDetails vfcResourceDetails;
+ protected ResourceReqDetails vfcmtResourceDetails;
+ protected ResourceReqDetails vfResourceDetails;
+
+
+ public static TestName name = new TestName();
+
+ public GetLeftPaletteTest() {
+ super(name, GetLeftPaletteTest.class.getName());
+ }
+
+ @BeforeClass
+ public void setUp() throws Exception {
+ // create VL
+ vlResourceDetails = createResource(vlResourceDetails, "vlRes", ResourceTypeEnum.VL);
+ checkInResource(vlResourceDetails);
+
+ // create CP
+ cpResourceDetails = createResource(cpResourceDetails, "cpRes", ResourceTypeEnum.CP);
+ checkInResource(cpResourceDetails);
+
+ // create VFC
+ vfcResourceDetails = createResource(vfcResourceDetails, "vfcRes", ResourceTypeEnum.VFC);
+ checkInResource(vfcResourceDetails);
+
+ // create VFCMT
+ vfcmtResourceDetails = createResource(vfcmtResourceDetails, "vfcmtRes", ResourceTypeEnum.VFCMT);
+ checkInResource(vfcmtResourceDetails);
+
+ // create VF
+ vfResourceDetails = createResource(vfResourceDetails, "vfRes", ResourceTypeEnum.VF);
+ checkInResource(vfResourceDetails);
+ }
+
+
+
+ @Test
+ public void testGetLeftPaletteForPNF() throws IOException {
+
+ RestResponse getResourceLatestVersionResponse = ResourceRestUtils.getResourceLatestVersionListMetadata(designerDetails, "PNF");
+ assertTrue("response code is not 200, returned :" + getResourceLatestVersionResponse.getErrorCode(),
+ getResourceLatestVersionResponse.getErrorCode() == 200);
+
+ String json = getResourceLatestVersionResponse.getResponse();
+ JSONArray jsonResp = (JSONArray) JSONValue.parse(json);
+
+ AssertJUnit.assertTrue("check vlResource is in response",
+ isComponentInArray(vlResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertTrue("check cpResource is in response",
+ isComponentInArray(cpResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertFalse("check vfcResource is not in response",
+ isComponentInArray(vfcResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertFalse("check vfResource is not in response",
+ isComponentInArray(vfResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertFalse("check vfcmtResource is not in response",
+ isComponentInArray(vfcmtResourceDetails.getUniqueId(), jsonResp));
+
+ }
+
+ @Test
+ public void testGetLeftPaletteForVF() throws IOException {
+
+ RestResponse getResourceLatestVersionResponse = ResourceRestUtils.getResourceLatestVersionListMetadata(designerDetails, "VF");
+ assertTrue("response code is not 200, returned :" + getResourceLatestVersionResponse.getErrorCode(),
+ getResourceLatestVersionResponse.getErrorCode() == 200);
+
+ String json = getResourceLatestVersionResponse.getResponse();
+ JSONArray jsonResp = (JSONArray) JSONValue.parse(json);
+
+ AssertJUnit.assertTrue("check vlResource is in response",
+ isComponentInArray(vlResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertTrue("check cpResource is in response",
+ isComponentInArray(cpResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertTrue("check vfcResource is not in response",
+ isComponentInArray(vfcResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertFalse("check vfResource is not in response",
+ isComponentInArray(vfResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertFalse("check vfcmtResource is not in response",
+ isComponentInArray(vfcmtResourceDetails.getUniqueId(), jsonResp));
+
+ }
+
+ @Test
+ public void testGetLeftPaletteForService() throws IOException {
+
+ RestResponse getResourceLatestVersionResponse = ResourceRestUtils.getResourceLatestVersionListMetadata(designerDetails, "SERVICE");
+ assertTrue("response code is not 200, returned :" + getResourceLatestVersionResponse.getErrorCode(),
+ getResourceLatestVersionResponse.getErrorCode() == 200);
+
+ String json = getResourceLatestVersionResponse.getResponse();
+ JSONArray jsonResp = (JSONArray) JSONValue.parse(json);
+
+ AssertJUnit.assertTrue("check vlResource is in response",
+ isComponentInArray(vlResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertTrue("check cpResource is in response",
+ isComponentInArray(cpResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertFalse("check vfcResource is not in response",
+ isComponentInArray(vfcResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertTrue("check vfResource is not in response",
+ isComponentInArray(vfResourceDetails.getUniqueId(), jsonResp));
+
+ AssertJUnit.assertFalse("check vfcmtResource is not in response",
+ isComponentInArray(vfcmtResourceDetails.getUniqueId(), jsonResp));
+
+ }
+
+ private ResourceReqDetails createResource(ResourceReqDetails resDetails, String name, ResourceTypeEnum resType) throws Exception {
+ resDetails = new ResourceReqDetails(name, "desc",Arrays.asList(name), "Generic", Arrays.asList("tosca.nodes.Root"), "c", "1", "111", "myIcon", resType.name());
+ resDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS.getCategory(),
+ ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS.getSubCategory());
+ RestResponse response = ResourceRestUtils.createResource(resDetails, designerDetails);
+ assertTrue("response code is not 200, returned :" + response.getErrorCode(),
+ response.getErrorCode() == 201);
+ resDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(response));
+ return resDetails;
+ }
+
+ private void checkInResource(ResourceReqDetails resDetails) throws IOException {
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resDetails, designerDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+ AssertJUnit.assertEquals("check in operation failed", 200, checkInResponse.getErrorCode().intValue());
+
+ }
+
+ protected boolean isComponentInArray(String id, JSONArray component) {
+ for (int i = 0; i < component.size(); i++) {
+ JSONObject jobject = (JSONObject) component.get(i);
+ if (jobject.get("uniqueId").toString().equals(id.toLowerCase())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @AfterClass
+ public void tearDown() throws IOException {
+ ResourceRestUtils.deleteResource(vlResourceDetails.getUniqueId(), designerDetails.getUserId());
+ ResourceRestUtils.deleteResource(cpResourceDetails.getUniqueId(), designerDetails.getUserId());
+ ResourceRestUtils.deleteResource(vfcResourceDetails.getUniqueId(), designerDetails.getUserId());
+ ResourceRestUtils.deleteResource(vfcmtResourceDetails.getUniqueId(), designerDetails.getUserId());
+ ResourceRestUtils.deleteResource(vfResourceDetails.getUniqueId(), designerDetails.getUserId());
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java
index 149febf05c..2939a8a09e 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java
@@ -34,13 +34,7 @@ import org.json.JSONArray;
import org.junit.rules.TestName;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.model.CapReqDef;
-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.RequirementCapabilityRelDef;
-import org.openecomp.sdc.be.model.RequirementDefinition;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
@@ -93,10 +87,13 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
createAtomicResource(resourceDetailsVFC_01);
createAtomicResource(resourceDetailsVFC_02);
createAtomicResource(resourceDetailsCP_01);
+ LifecycleRestUtils.changeResourceState(resourceDetailsCP_01, sdncAdminDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
createAtomicResource(resourceDetailsVL_01);
createAtomicResource(resourceDetailsVL_02);
createVF(resourceDetailsVF_01);
createVF(resourceDetailsVF_02);
+ createPNF(resourceDetailsPNF_01);
createService(serviceDetails_01);
certifyResource(resourceDetailsVFC_01);
certifyResource(resourceDetailsVFC_02);
@@ -173,6 +170,10 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
return createVFInstance(containerDetails, compInstOriginDetails, modifier);
}
+ private RestResponse createCheckedinPNFInstance(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ return createCheckedinVFInstance(containerDetails, compInstOriginDetails, modifier);
+ }
+
private RestResponse createCheckedinAtomicInstanceForService(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
changeResourceLifecycleState(compInstOriginDetails, compInstOriginDetails.getCreatorUserId(), LifeCycleStatesEnum.CHECKIN);
return createAtomicInstanceForService(containerDetails, compInstOriginDetails, modifier);
@@ -205,6 +206,16 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
}
@Test
+ public void createPNFInstanceSuccessfullyTest() throws Exception {
+ RestResponse createPNFInstResp = createCheckedinPNFInstance(serviceDetails_01, resourceDetailsPNF_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createPNFInstResp);
+ getComponentAndValidateRIs(serviceDetails_01, 1, 0);
+// createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
+// ResourceRestUtils.checkCreateResponse(createVFInstResp);
+// getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
+ @Test
public void createVFAndAtomicInstanceTest() throws Exception {
RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
ResourceRestUtils.checkCreateResponse(createVFInstResp);
@@ -218,6 +229,56 @@ public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest
}
@Test
+ public void createPNFAndAtomicInstanceTest() throws Exception {
+ RestResponse createPNFInstResp = createCheckedinPNFInstance(serviceDetails_01, resourceDetailsPNF_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createPNFInstResp);
+ RestResponse createVLInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVLInstResp);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+
+
+ }
+
+ private String createCpInstance() throws Exception {
+ // Create CP instance
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsPNF_01,
+ resourceDetailsCP_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ getComponentAndValidateRIs(resourceDetailsPNF_01, 1, 0);
+ return ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+ }
+
+ @Test
+ public void createPNFAndAtomicInstanceAssociatedTest() throws Exception {
+ reqOwnerId = createCpInstance();
+ RestResponse createPNFInstResp = createCheckedinPNFInstance(serviceDetails_01, resourceDetailsPNF_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createPNFInstResp);
+ String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createPNFInstResp);
+ RestResponse createVLInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVLInstResp);
+ capOwnerId = ResponseParser.getUniqueIdFromResponse(createVLInstResp);
+ String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVLInstResp);
+
+ String capType = "tosca.capabilities.network.Linkable";
+ String reqName = "link";
+
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ ResourceRestUtils.checkSuccess(getResourceResponse);
+ CapReqDef capReqDef = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), CapReqDef.class);
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName, capList, reqList);
+
+ associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
+ getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ capReqDef = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), CapReqDef.class);
+ List<RequirementDefinition> list = capReqDef.getRequirements().get(capType);
+// AssertJUnit.assertEquals("Check requirement", null, list);
+ getComponentAndValidateRIsOnly(serviceDetails_01, 2, 1);
+ }
+
+ @Test
public void deleteAtomicInstanceTest() throws Exception {
RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
// 1 rel
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java
index 85b01e6d2b..6bfa1b8e94 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DistributionUtils.java
@@ -63,7 +63,7 @@ import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
//
public class DistributionUtils {
- final static String serviceDistributionSuffix = "/asdc/v1/catalog/services/";
+ final static String serviceDistributionSuffix = "/sdc/v1/catalog/services/";
public static ServiceDistributionStatus getLatestServiceDistributionObject(Service service) throws IOException, ParseException {
ServiceDistributionStatus serviceDistributionStatus = null;
@@ -124,13 +124,13 @@ import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
}
private static String buildServiceDeploymentUrl(Service service, String artifactName, String artifactUUID) {
-// format "/asdc/v1/catalog/services/" + service.getSystemName() + "/" + service.getVersion() + "/artifacts/AAI-" + service.getName() + "-service-1.xml"
+// format "/sdc/v1/catalog/services/" + service.getSystemName() + "/" + service.getVersion() + "/artifacts/AAI-" + service.getName() + "-service-1.xml"
return serviceDistributionSuffix + service.getSystemName() + "/" + service.getVersion() + "/artifacts/" + artifactName;
}
public static String buildResourceInstanceDeploymentUrl(Service service, String artifactName, String artifactUUID){
-// /asdc/v1/catalog/services/Servicefordistribution/1.0 /resourceInstances/nestedfrommarina2 /artifacts/FEAdd_On_Module_vProbeLauncher.yaml
+// /sdc/v1/catalog/services/Servicefordistribution/1.0 /resourceInstances/nestedfrommarina2 /artifacts/FEAdd_On_Module_vProbeLauncher.yaml
String resourceInstanceNormalizedName = getResourceInstanceNormalizeName(service, artifactName, artifactUUID );
return serviceDistributionSuffix + service.getSystemName() + "/" + service.getVersion() + "/resourceInstances/" + resourceInstanceNormalizedName +"/artifacts/" + artifactName;
}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java
index c06cb570f8..1578b6eba0 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java
@@ -689,7 +689,7 @@ public class ElementFactory {
ExpectedExternalAudit expectedExternalAudit = new ExpectedExternalAudit();
expectedExternalAudit.setACTION(action.getName());
expectedExternalAudit.setCONSUMER_ID("ci");
- expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetType.getValue() + (query == null ? "" : query));
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetType.getValue() + (query == null ? "" : query));
expectedExternalAudit.setSTATUS("200");
expectedExternalAudit.setDESC("OK");
return expectedExternalAudit;
@@ -752,7 +752,7 @@ public class ElementFactory {
expectedResourceAuditJavaObject.setResourceName(resourceName);
expectedResourceAuditJavaObject.setResourceType("Resource");
expectedResourceAuditJavaObject.setCONSUMER_ID("ci");
- expectedResourceAuditJavaObject.setRESOURCE_URL("/asdc/v1/catalog/resources");
+ expectedResourceAuditJavaObject.setRESOURCE_URL("/sdc/v1/catalog/resources");
expectedResourceAuditJavaObject.setMODIFIER("");
expectedResourceAuditJavaObject.setPrevVersion("");
expectedResourceAuditJavaObject.setCurrVersion("0.1");
@@ -769,7 +769,7 @@ public class ElementFactory {
public static ExpectedExternalAudit getDefaultExternalArtifactAuditSuccess(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, String componentUUID, String resourceInstanceName) {
ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalArtifactAuditSuccess(assetType, action, artifactDefinition, componentUUID);
- expectedExternalArtifactAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetType.getValue() + "/" + componentUUID + "/resourceInstances/" + resourceInstanceName + "/artifacts");
+ expectedExternalArtifactAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetType.getValue() + "/" + componentUUID + "/resourceInstances/" + resourceInstanceName + "/artifacts");
return expectedExternalArtifactAudit;
}
@@ -794,7 +794,7 @@ public class ElementFactory {
String resourceInstanceName) {
ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalArtifactAuditFailure(assetType, action, artifactDefinition, componentUUID, errorInfo, variables);
- expectedExternalArtifactAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetType.getValue() + "/" + componentUUID + "/resourceInstances/" + resourceInstanceName + "/artifacts");
+ expectedExternalArtifactAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetType.getValue() + "/" + componentUUID + "/resourceInstances/" + resourceInstanceName + "/artifacts");
return expectedExternalArtifactAudit;
}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java
index 7272e345ae..5565780dd5 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java
@@ -76,10 +76,10 @@ public class AssetRestUtils extends BaseRestUtils {
static final String contentTypeHeaderData = "application/json";
static final String acceptHeaderDate = "application/json";
static final String basicAuthentication = "Basic Y2k6MTIzNDU2";
- // /asdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID}
- static final String COMPONENT_ARTIFACT_URL = "/asdc/v1/catalog/%s/%s/artifacts/%s";
- // /asdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}
- static final String RESOURCE_INSTANCE_ARTIFACT_URL = "/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
+ // /sdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID}
+ static final String COMPONENT_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/artifacts/%s";
+ // /sdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}
+ static final String RESOURCE_INSTANCE_ARTIFACT_URL = "/sdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
public static HttpResponse getComponentToscaModel(AssetTypeEnum assetType, String uuid) throws IOException {
Config config = Utils.getConfig();
@@ -338,7 +338,7 @@ public class AssetRestUtils extends BaseRestUtils {
// assertNotNull("Expected artifact asset resourceInvariantUUID
// is null",
// resourceInstanceAssetStructure.getResourceInvariantUUID());
- // String expectedArtifactUrl = "/asdc/v1/catalog/" +
+ // String expectedArtifactUrl = "/sdc/v1/catalog/" +
// assetType.getValue() + "/" + componentUuid + "/artifacts/" +
// componentDeploymentArtifactValue.getArtifactUUID();
String expectedArtifactUrl = "";
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java
index a265639804..522a91f7d3 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java
@@ -21,8 +21,7 @@
package org.openecomp.sdc.ci.tests.utils.rest;
import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
+import java.util.*;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.config.Config;
@@ -52,6 +51,15 @@ public class CatalogRestUtils extends BaseRestUtils {
return sendGet(url, userId);
}
+ public static RestResponse getCatalog(String userId, List<String> excludeList) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_CATALOG_DATA, config.getCatalogBeHost(), config.getCatalogBePort());
+ StringBuilder sb = new StringBuilder();
+ sb.append(url).append("?");
+ Optional.ofNullable(excludeList).orElse(Collections.emptyList()).forEach(type -> sb.append("excludeTypes="+type+"&"));
+ return sendGet(sb.toString(), userId);
+ }
+
public static RestResponse getAllCategoriesTowardsCatalogBe() throws IOException {
Config config = Utils.getConfig();
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CommonRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CommonRestUtils.java
new file mode 100644
index 0000000000..bc807df7fa
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CommonRestUtils.java
@@ -0,0 +1,23 @@
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+
+public class CommonRestUtils extends BaseRestUtils {
+
+ private static Logger logger = LoggerFactory.getLogger(CommonRestUtils.class.getName());
+
+ public static RestResponse getHealthCheck() throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_HEALTH_CHECK_VIA_PROXY, config.getCatalogFeHost(), config.getCatalogFePort());
+
+ return sendGet(url, null);
+
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java
index 90371662a7..b17deb3756 100644
--- a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java
@@ -254,6 +254,20 @@ public class ResourceRestUtils extends BaseRestUtils {
return sendGet(url, sdncModifierDetails.getUserId());
}
+ public static RestResponse getResourceLatestVersionListMetadata(User sdncModifierDetails, String internalComponentType) throws IOException {
+
+ Config config = Utils.getConfig();
+ StringBuilder sb = new StringBuilder();
+ String url = String.format(Urls.GET_RESOURCE_METADATA_lATEST_VERSION, config.getCatalogBeHost(),
+ config.getCatalogBePort());
+ sb.append(url);
+ if (internalComponentType != null && !internalComponentType.isEmpty()) {
+ sb.append("?internalComponentType="+internalComponentType);
+ }
+ return sendGet(sb.toString(), sdncModifierDetails.getUserId());
+
+ }
+
public static RestResponse getResourceByNameAndVersion(String userId, String resourceName, String resourceVersion)
throws IOException {
diff --git a/asdctool/pom.xml b/asdctool/pom.xml
index da1b9160fd..40eebbab5f 100644
--- a/asdctool/pom.xml
+++ b/asdctool/pom.xml
@@ -76,6 +76,12 @@
</dependency>
<dependency>
+ <groupId>commons-cli</groupId>
+ <artifactId>commons-cli</artifactId>
+ <version>1.4</version>
+ </dependency>
+
+ <dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
@@ -417,6 +423,20 @@
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
+
+ <dependency>
+ <groupId>org.testng</groupId>
+ <artifactId>testng</artifactId>
+ <version>${testng.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <version>${mockito.version}</version>
+ <scope>test</scope>
+ </dependency>
<!-- testing end -->
</dependencies>
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
index ee5171d8ab..0ef435e1c3 100644
--- 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
@@ -706,7 +706,7 @@ public class ServiceMigration {
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 capabilty component instance for relation {}, error {}", rel.getUniqueId(), reqInst.right().value());
+ 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();
@@ -917,6 +917,9 @@ public class ServiceMigration {
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;
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
index c14301ae5e..b3f138241e 100644
--- 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
@@ -103,10 +103,10 @@ public class Migration1707ArtifactUuidFix {
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 withh failure", runMode);
+ log.info("Mode {}. Fix finished with failure", runMode);
return false;
}
- log.info("Mode {}. Fix finished withh success", runMode);
+ log.info("Mode {}. Fix finished with success", runMode);
}
return true;
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
index 21a6ae1416..36919d7520 100644
--- 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
@@ -271,4 +271,9 @@ public class Migration1707Config {
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
new file mode 100644
index 0000000000..ff41f12b8e
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/Migration1707MissingInfoFix.java
@@ -0,0 +1,220 @@
+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/jsonmodel/ComponentMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/impl/migration/v1707/jsonmodel/ComponentMigration.java
index d69363be89..7603a5704a 100644
--- 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
@@ -109,8 +109,8 @@ public abstract class ComponentMigration <T extends Component> extends JsonModel
protected void setMissingTemplateInfo(List<T> components) {
Map<String, ToscaElement> origCompMap = new HashMap<>();
for (T component : components) {
- List<ComponentInstance> instances = component.getComponentInstances();
- if(null != instances) {
+ List<ComponentInstance> instances = component.getComponentInstances();
+ if(null != instances) {
for (ComponentInstance instance : instances) {
nodeTemplateMissingDataResolver.resolveNodeTemplateInfo(instance, origCompMap, component);
nodeTemplateMissingDataResolver.fixVFGroupInstances(component, instance);
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
index 01e36345e1..c83421066c 100644
--- 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
@@ -17,23 +17,18 @@
* 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.ArtifactDefinition;
-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.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
+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;
@@ -45,6 +40,8 @@ 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;
@@ -59,32 +56,98 @@ public class NodeTemplateMissingDataResolver <T extends Component> {
private ToscaElementLifecycleOperation lifecycleOperation;
@Resource(name = "topology-template-operation")
- private TopologyTemplateOperation topologyTemplateOperation;
+ public TopologyTemplateOperation topologyTemplateOperation;
public void resolveNodeTemplateInfo(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap, T component) {
lifecycleOperation.resolveToscaComponentName(vfInst, origCompMap);
if(OriginTypeEnum.VF == vfInst.getOriginType()) {
- Map<String, List<ComponentInstanceInput>> componentInstancesInputs = Optional.ofNullable(component.getComponentInstancesInputs()).orElse(new HashMap<>());
- collectVFInstanceInputs(componentInstancesInputs, origCompMap, vfInst);
+ 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 void collectVFInstanceInputs(Map<String, List<ComponentInstanceInput>> instInputs, Map<String, ToscaElement> origCompMap, ComponentInstanceDataDefinition vfInst) {
+ 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;
+ 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 = instInputs.get(ciUid);
+
+ List<ComponentInstanceInput> instInputList = componentInstInputs.get(ciUid);
Map<String, ComponentInstanceInput> existingInstInputs = ToscaDataDefinition.listToMapByName(instInputList);
collectedVFInputs.putAll(existingInstInputs);
List<ComponentInstanceInput> mergedList = new ArrayList<>(collectedVFInputs.values());
- instInputs.put(ciUid, mergedList);
+ componentInstInputs.put(ciUid, mergedList);
}
+ return res;
}
private Either<ToscaElement, StorageOperationStatus> fetchToscaElement(Map<String, ToscaElement> origCompMap, ComponentInstanceDataDefinition vfInst, String origCompUid) {
@@ -201,22 +264,23 @@ public class NodeTemplateMissingDataResolver <T extends Component> {
return artifactLabel;
}
- protected boolean fixVFGroups(Component component){
- boolean res = true;
-
+ 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());
+ 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)) {
- List<String> groupArtifacts = new ArrayList<String>(group.getArtifacts());
- group.getArtifacts().clear();
- group.getArtifactsUuid().clear();
+ 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);
@@ -229,19 +293,16 @@ public class NodeTemplateMissingDataResolver <T extends Component> {
if (correctArtifactUUID != null && !correctArtifactUUID.isEmpty()) {
group.getArtifactsUuid().add(correctArtifactUUID);
}
-
}
}
}
}
-
- }
-
+ }
return res;
}
- protected boolean fixVFGroupInstances(Component component, ComponentInstance instance){
- boolean res = true;
+ public boolean fixVFGroupInstances(Component component, ComponentInstance instance){
+ boolean res = false;
Map<String, ArtifactDefinition> deploymentArtifacts = instance.getDeploymentArtifacts();
List<GroupInstance> groupInstances = instance.getGroupInstances();
@@ -252,10 +313,9 @@ public class NodeTemplateMissingDataResolver <T extends Component> {
for (GroupInstance group : groupInstances) {
if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
if (isProblematicGroupInstance(group, instance.getName(), component.getName(), deploymentArtifacts)) {
-
- LOGGER.debug("Migration1707ArtifactUuidFix fix group: resource id {}, group name {} ", component.getUniqueId(), group.getName());
- List<String> groupArtifacts = Optional.ofNullable(group.getArtifacts()).orElse(new ArrayList<>());
-
+ 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<>());
@@ -285,12 +345,9 @@ public class NodeTemplateMissingDataResolver <T extends Component> {
}
}
}
-
}
}
}
-
return res;
}
-
}
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
index dd9fa86084..600ebf848a 100644
--- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/MigrationMenu.java
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/main/MigrationMenu.java
@@ -33,12 +33,7 @@ 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.Migration1707;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.Migration1707ArtifactUuidFix;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.Migration1707Config;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.DistributionStatusUpdate;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.Migration1707VnfFix;
-import org.openecomp.sdc.asdctool.impl.migration.v1707.VfModulesPropertiesAdding;
+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;
@@ -53,17 +48,17 @@ public class MigrationMenu {
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"),
+ 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"),
@@ -71,7 +66,8 @@ public class MigrationMenu {
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_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;
@@ -225,7 +221,7 @@ public class MigrationMenu {
ToscaArtifactsAlignment toscaArtifactsAlignment = (ToscaArtifactsAlignment) context.getBean(operationEnum.getBeanName());
boolean isSuccessful = toscaArtifactsAlignment.alignToscaArtifacts();
if (isSuccessful) {
- log.info("Tosca Artifacts alignment was finished successfull");
+ log.info("Tosca Artifacts alignment was finished successfully");
System.exit(0);
} else {
log.info("Tosca Artifacts alignment has failed");
@@ -233,20 +229,20 @@ public class MigrationMenu {
}
break;
case MIGRATION_1610_1702:
- log.info("Start ASDC migration from 1610 to 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("ASDC migration from 1610 to 1702 was finished successful");
+ log.info("SDC migration from 1610 to 1702 was finished successful");
System.exit(0);
} else{
- log.info("ASDC migration from 1610 to 1702 has failed");
+ 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 ASDC migration from 1702 to 1707");
+// log.info("Start SDC migration from 1702 to 1707");
Migration1707 migration1707 = (Migration1707) context.getBean(operationEnum.getBeanName());
isSuccessful = migration1707.migrate();
if (isSuccessful) {
@@ -278,8 +274,8 @@ public class MigrationMenu {
}
String fixServices = args[3];
String runMode = args[4];
- log.info("Start fixing artifact UUID after 1707 migration with arguments run with configutation [{}] , for [{}] services", runMode, fixServices);
-
+ 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) {
@@ -290,6 +286,20 @@ public class MigrationMenu {
}
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();
}
@@ -330,5 +340,6 @@ public class MigrationMenu {
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/migration/config/MigrationSpringConfig.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/MigrationSpringConfig.java
new file mode 100644
index 0000000000..0457c2136d
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/config/MigrationSpringConfig.java
@@ -0,0 +1,59 @@
+package org.openecomp.sdc.asdctool.migration.config;
+
+import org.openecomp.sdc.asdctool.migration.core.SdcMigrationTool;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.resolver.MigrationResolver;
+import org.openecomp.sdc.asdctool.migration.resolver.SpringBeansMigrationResolver;
+import org.openecomp.sdc.asdctool.migration.service.SdcRepoService;
+import org.openecomp.sdc.be.dao.cassandra.CassandraClient;
+import org.openecomp.sdc.be.dao.cassandra.MigrationTasksDao;
+import org.openecomp.sdc.be.dao.config.DAOSpringConfig;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@Configuration
+@Import(DAOSpringConfig.class)
+@ComponentScan({"org.openecomp.sdc.asdctool.migration.tasks",//migration tasks
+ "org.openecomp.sdc.be.model.operations.impl",
+ "org.openecomp.sdc.be.model.cache",
+ "org.openecomp.sdc.be.dao.titan",
+ "org.openecomp.sdc.be.dao.cassandra",
+ "org.openecomp.sdc.be.model.jsontitan.operations",
+ "org.openecomp.sdc.be.dao.jsongraph"})
+public class MigrationSpringConfig {
+
+ @Autowired(required=false)
+ private List<Migration> migrations = new ArrayList<>();
+
+ @Bean(name = "sdc-migration-tool")
+ public SdcMigrationTool sdcMigrationTool(MigrationResolver migrationResolver, SdcRepoService sdcRepoService) {
+ return new SdcMigrationTool(migrationResolver, sdcRepoService);
+ }
+
+ @Bean(name = "spring-migrations-resolver")
+ public SpringBeansMigrationResolver migrationResolver(SdcRepoService sdcRepoService) {
+ return new SpringBeansMigrationResolver(migrations, sdcRepoService);
+ }
+
+ @Bean(name = "sdc-repo-service")
+ public SdcRepoService sdcRepoService(MigrationTasksDao migrationTasksDao) {
+ return new SdcRepoService(migrationTasksDao);
+ }
+
+ @Bean(name = "sdc-migration-tasks-cassandra-dao")
+ public MigrationTasksDao migrationTasksDao() {
+ return new MigrationTasksDao();
+ }
+
+ @Bean(name = "cassandra-client")
+ public CassandraClient cassandraClient() {
+ return new CassandraClient();
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/DBVersion.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/DBVersion.java
new file mode 100644
index 0000000000..003a27a1e4
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/DBVersion.java
@@ -0,0 +1,95 @@
+package org.openecomp.sdc.asdctool.migration.core;
+
+import java.math.BigInteger;
+
+public class DBVersion implements Comparable<DBVersion>{
+
+ private static final String VERSION_PARTS_SEPARATOR = "\\.";
+ private static final int MAJOR_PART_IDX = 0;
+ private static final int MINOR_PART_IDX = 1;
+ private BigInteger major;
+ private BigInteger minor;
+
+ /**
+ * The current db version. should be tested against real db to verify it is compatible to the db version
+ */
+ public static final DBVersion CURRENT_VERSION = new DBVersion(1710, 0);
+
+ private DBVersion(BigInteger major, BigInteger minor) {
+ this.major = major;
+ this.minor = minor;
+ }
+
+ private DBVersion(int major, int minor) {
+ this.major = BigInteger.valueOf(major);
+ this.minor = BigInteger.valueOf(minor);
+ }
+
+ public BigInteger getMajor() {
+ return major;
+ }
+
+ public BigInteger getMinor() {
+ return minor;
+ }
+
+ public static DBVersion from(BigInteger major, BigInteger minor) {
+ return new DBVersion(major, minor);
+ }
+
+ public static DBVersion fromString(String version) {
+ String[] split = version.split(VERSION_PARTS_SEPARATOR);
+ if (split.length != 2) {
+ throw new MigrationException("version must be of pattern: <major>.<minor>");
+ }
+ return new DBVersion(getVersionPart(split[MAJOR_PART_IDX]),
+ getVersionPart(split[MINOR_PART_IDX]));
+
+ }
+
+ private static BigInteger getVersionPart(String versionPart) {
+ try {
+ return new BigInteger(versionPart);
+ } catch (NumberFormatException e) {
+ throw new MigrationException(String.format("version part %s is non numeric", versionPart));
+ }
+ }
+
+ @Override
+ public String toString() {
+ return String.format("%s.%s", major, minor);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ DBVersion dbVersion = (DBVersion) o;
+
+ return major.equals(dbVersion.major) && minor.equals(dbVersion.minor);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = major.hashCode();
+ result = 31 * result + minor.hashCode();
+ return result;
+ }
+
+ @Override
+ public int compareTo(DBVersion o) {
+ if (o == null) {
+ return 1;
+ }
+ int majorsComparision = this.major.compareTo(o.major);
+ if (majorsComparision != 0) {
+ return majorsComparision;
+ }
+ int minorsComparision = this.minor.compareTo(o.minor);
+ if (minorsComparision != 0) {
+ return minorsComparision;
+ }
+ return 0;
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/MigrationException.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/MigrationException.java
new file mode 100644
index 0000000000..e9e805355e
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/MigrationException.java
@@ -0,0 +1,13 @@
+package org.openecomp.sdc.asdctool.migration.core;
+
+public class MigrationException extends RuntimeException {
+
+ public MigrationException(String message) {
+ super(message);
+ }
+
+ public MigrationException(String message, RuntimeException e) {
+ super(message, e);
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/SdcMigrationTool.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/SdcMigrationTool.java
new file mode 100644
index 0000000000..e2691dc7f8
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/SdcMigrationTool.java
@@ -0,0 +1,62 @@
+package org.openecomp.sdc.asdctool.migration.core;
+
+import org.openecomp.sdc.asdctool.migration.core.execution.MigrationExecutionResult;
+import org.openecomp.sdc.asdctool.migration.core.execution.MigrationExecutorImpl;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+import org.openecomp.sdc.asdctool.migration.resolver.MigrationResolver;
+import org.openecomp.sdc.asdctool.migration.service.SdcRepoService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+
+public class SdcMigrationTool {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(SdcMigrationTool.class);
+
+ private MigrationResolver migrationsResolver;
+
+ private SdcRepoService sdcRepoService;
+
+ public SdcMigrationTool(MigrationResolver migrationsResolver, SdcRepoService sdcRepoService) {
+ this.migrationsResolver = migrationsResolver;
+ this.sdcRepoService = sdcRepoService;
+ }
+
+ public SdcMigrationTool() {
+ }
+
+ public boolean migrate(boolean enforceAll) {
+ LOGGER.info("starting migration process");
+ handleEnforceMigrationFlag(enforceAll);
+ List<Migration> migrations = migrationsResolver.resolveMigrations();
+ LOGGER.info("there are {} migrations task to execute", migrations.size());
+ for (Migration migration : migrations) {
+ try {
+ MigrationExecutionResult executionResult = new MigrationExecutorImpl().execute(migration);
+ if (migrationHasFailed(executionResult)) {
+ LOGGER.error("migration {} with version {} has failed. error msg: {}", migration.getClass().getName(), migration.getVersion().toString(), executionResult.getMsg());
+ return false;
+ }
+ sdcRepoService.createMigrationTask(executionResult.toMigrationTaskEntry());
+ } catch (RuntimeException e) {
+ LOGGER.error("migration {} with version {} has failed. error msg: {}", migration.getClass().getName(), migration.getVersion().toString(), e);
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private boolean migrationHasFailed(MigrationExecutionResult migrationResult) {
+ return migrationResult.getMigrationStatus().equals(MigrationResult.MigrationStatus.FAILED);
+ }
+
+ private void handleEnforceMigrationFlag(boolean enforceAll) {
+ if (enforceAll) {
+ LOGGER.info("enforcing migration for current version");
+ sdcRepoService.clearTasksForCurrentMajor();
+ }
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutionResult.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutionResult.java
new file mode 100644
index 0000000000..4ebec6e440
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutionResult.java
@@ -0,0 +1,70 @@
+package org.openecomp.sdc.asdctool.migration.core.execution;
+
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+import org.openecomp.sdc.be.resources.data.MigrationTaskEntry;
+
+import java.util.Date;
+
+public class MigrationExecutionResult {
+
+ private MigrationResult.MigrationStatus migrationStatus;
+ private String msg;
+ private double executionTime;
+ private DBVersion version;
+ private String taskName;
+
+ public MigrationTaskEntry toMigrationTaskEntry() {
+ MigrationTaskEntry migrationTaskEntry = new MigrationTaskEntry();
+ migrationTaskEntry.setMajorVersion(this.getVersion().getMajor().longValue());
+ migrationTaskEntry.setMinorVersion(this.getVersion().getMinor().longValue());
+ migrationTaskEntry.setTimestamp(new Date());
+ migrationTaskEntry.setTaskName(this.getTaskName());
+ migrationTaskEntry.setTaskStatus(this.getMigrationStatus().name());
+ migrationTaskEntry.setMessage(this.getMsg());
+ migrationTaskEntry.setExecutionTime(this.getExecutionTime());
+ return migrationTaskEntry;
+ }
+
+
+ public MigrationResult.MigrationStatus getMigrationStatus() {
+ return migrationStatus;
+ }
+
+ void setMigrationStatus(MigrationResult.MigrationStatus migrationStatus) {
+ this.migrationStatus = migrationStatus;
+ }
+
+ public String getMsg() {
+ return msg;
+ }
+
+ void setMsg(String msg) {
+ this.msg = msg;
+ }
+
+ double getExecutionTime() {
+ return executionTime;
+ }
+
+ void setExecutionTime(double executionTime) {
+ this.executionTime = executionTime;
+ }
+
+ public DBVersion getVersion() {
+ return version;
+ }
+
+ public void setVersion(DBVersion version) {
+ this.version = version;
+ }
+
+ String getTaskName() {
+ return taskName;
+ }
+
+ void setTaskName(String taskName) {
+ this.taskName = taskName;
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutor.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutor.java
new file mode 100644
index 0000000000..aba5056b48
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutor.java
@@ -0,0 +1,15 @@
+package org.openecomp.sdc.asdctool.migration.core.execution;
+
+import org.openecomp.sdc.asdctool.migration.core.MigrationException;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+
+public interface MigrationExecutor {
+
+ /**
+ * @param migration the migration to execute
+ * @return a {@link MigrationExecutionResult} with the relevant data on the current migration execution;
+ * @throws MigrationException in case there was an unexpected exception during migration
+ */
+ MigrationExecutionResult execute(Migration migration) throws MigrationException;
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutorImpl.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutorImpl.java
new file mode 100644
index 0000000000..2e4d3ba8b0
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutorImpl.java
@@ -0,0 +1,47 @@
+package org.openecomp.sdc.asdctool.migration.core.execution;
+
+import org.openecomp.sdc.asdctool.migration.core.MigrationException;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.util.StopWatch;
+
+
+public class MigrationExecutorImpl implements MigrationExecutor {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(MigrationExecutorImpl.class);
+
+ @Override
+ public MigrationExecutionResult execute(Migration migration) throws MigrationException {
+ try {
+ LOGGER.info("starting migration {}. description: {}. version {}", migration.getClass().getName(), migration.description(), migration.getVersion().toString());
+ StopWatch stopWatch = new StopWatch();
+ stopWatch.start();
+ MigrationResult migrationResult = migration.migrate();
+ stopWatch.stop();
+ double executionTime = stopWatch.getTotalTimeSeconds();
+ return logAndCreateExecutionResult(migration, migrationResult, executionTime);
+ } catch (RuntimeException e) {
+ LOGGER.error("migration {} has failed!", migration.description(), e);
+ throw new MigrationException("migration %s failed!!!", e);
+
+ }
+ }
+
+ private MigrationExecutionResult logAndCreateExecutionResult(Migration migration, MigrationResult migrationResult, double executionTime) {
+ LOGGER.info("finished migration {}. with version {}. migration status: {}, migration message: {}, execution time: {}", migration.getClass().getName(), migration.getVersion().toString(), migrationResult.getMigrationStatus().name(), migrationResult.getMsg(), executionTime);
+ return createMigrationTask(migration, migrationResult, executionTime);
+ }
+
+ private MigrationExecutionResult createMigrationTask(Migration migration, MigrationResult migrationResult, double totalTimeSeconds) {
+ MigrationExecutionResult migrationExecutionResult = new MigrationExecutionResult();
+ migrationExecutionResult.setExecutionTime(totalTimeSeconds);
+ migrationExecutionResult.setMigrationStatus(migrationResult.getMigrationStatus());
+ migrationExecutionResult.setMsg(migrationResult.getMsg());
+ migrationExecutionResult.setTaskName(migration.getClass().getName());
+ migrationExecutionResult.setVersion(migration.getVersion());
+ return migrationExecutionResult;
+ }
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/task/Migration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/task/Migration.java
new file mode 100644
index 0000000000..58f201acf5
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/task/Migration.java
@@ -0,0 +1,14 @@
+package org.openecomp.sdc.asdctool.migration.core.task;
+
+
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+
+public interface Migration {
+
+ String description();
+
+ DBVersion getVersion();
+
+ MigrationResult migrate();
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/task/MigrationResult.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/task/MigrationResult.java
new file mode 100644
index 0000000000..8c4c090d94
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/core/task/MigrationResult.java
@@ -0,0 +1,31 @@
+package org.openecomp.sdc.asdctool.migration.core.task;
+
+public class MigrationResult {
+
+ private String msg;
+ private MigrationStatus migrationStatus;
+
+ public String getMsg() {
+ return msg;
+ }
+
+ public void setMsg(String msg) {
+ this.msg = msg;
+ }
+
+ public MigrationStatus getMigrationStatus() {
+ return migrationStatus;
+ }
+
+ public void setMigrationStatus(MigrationStatus migrationStatus) {
+ this.migrationStatus = migrationStatus;
+ }
+
+ public enum MigrationStatus {
+ COMPLETED,
+ COMPLETED_WITH_ERRORS,
+ FAILED
+ }
+
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/main/MigrationMenu.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/main/MigrationMenu.java
new file mode 100644
index 0000000000..1e8a533624
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/main/MigrationMenu.java
@@ -0,0 +1,100 @@
+package org.openecomp.sdc.asdctool.migration.main;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.DefaultParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.openecomp.sdc.asdctool.migration.config.MigrationSpringConfig;
+import org.openecomp.sdc.asdctool.migration.core.SdcMigrationTool;
+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 final static Logger LOGGER = LoggerFactory.getLogger(MigrationMenu.class);
+
+ public static void main(String[] args) {
+ CommandLine commandLine = initCmdLineOptions(args);
+ String appConfigDir = commandLine.getOptionValue("c");
+ boolean enforceAll = commandLine.hasOption("e");
+ uploadConfiguration(appConfigDir);
+ AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MigrationSpringConfig.class);
+ doMigrate(enforceAll, context);
+
+ }
+
+ private static void doMigrate(boolean enforceAll, AnnotationConfigApplicationContext context) {
+ SdcMigrationTool migrationTool = context.getBean(SdcMigrationTool.class);
+ boolean migrate = migrationTool.migrate(enforceAll);
+ if (migrate) {
+ LOGGER.info("migration completed successfully");
+ System.exit(0);
+ } else {
+ LOGGER.error("migration failed");
+ System.exit(1);
+ }
+ }
+
+ private static CommandLine initCmdLineOptions(String[] args) {
+ Options options = buildCmdLineOptions();
+ CommandLineParser parser = new DefaultParser();
+ try {
+ // parse the command line arguments
+ return parser.parse( options, args );
+ }
+ catch( ParseException exp ) {
+ // oops, something went wrong
+ System.err.println( "Parsing failed. Reason: " + exp.getMessage() );
+ usageAndExit(options);
+ }
+ return null;
+ }
+
+ private static void usageAndExit(Options options) {
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.printHelp( "yy", options );
+ System.exit(1);
+ }
+
+ private static Options buildCmdLineOptions() {
+ Option configPath = buildConfigPathOption();
+
+ Option enforceAll = buildEnforceAllOption();
+
+ Options options = new Options();
+ options.addOption(configPath);
+ options.addOption(enforceAll);
+ return options;
+ }
+
+ private static Option buildEnforceAllOption() {
+ return Option.builder("e")
+ .longOpt("enforceAll")
+ .desc("enforce running all migration steps for current version")
+ .build();
+ }
+
+ private static Option buildConfigPathOption() {
+ return Option.builder("c")
+ .longOpt("configFolderPath")
+ .required()
+ .hasArg()
+ .desc("path to sdc configuration folder - required")
+ .build();
+ }
+
+ private static void uploadConfiguration(String appConfigDir) {
+ ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
+ ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
+ }
+
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/MigrationResolver.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/MigrationResolver.java
new file mode 100644
index 0000000000..b272d45ff0
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/MigrationResolver.java
@@ -0,0 +1,16 @@
+package org.openecomp.sdc.asdctool.migration.resolver;
+
+
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+
+import java.util.List;
+
+public interface MigrationResolver {
+
+ /**
+ *
+ * @return a list of {@code T}
+ */
+ List<Migration> resolveMigrations();
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/SpringBeansMigrationResolver.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/SpringBeansMigrationResolver.java
new file mode 100644
index 0000000000..4af5d76123
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/resolver/SpringBeansMigrationResolver.java
@@ -0,0 +1,45 @@
+package org.openecomp.sdc.asdctool.migration.resolver;
+
+
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.service.SdcRepoService;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class SpringBeansMigrationResolver implements MigrationResolver {
+
+ private List<Migration> migrations = new ArrayList<>();
+
+ private SdcRepoService sdcRepoService;
+
+ public SpringBeansMigrationResolver(List<Migration> migrations, SdcRepoService sdcRepoService) {
+ this.migrations = migrations;
+ this.sdcRepoService = sdcRepoService;
+ }
+
+ @Override
+ public List<Migration> resolveMigrations() {
+ migrations.sort(Comparator.comparing(Migration::getVersion));
+ return resolveNonExecutedMigrations();
+ }
+
+ //package private for testing
+ void setMigrations(List<Migration> migrations) {
+ this.migrations = migrations;
+ }
+
+ private List<Migration> resolveNonExecutedMigrations() {
+ DBVersion latestDBVersion = sdcRepoService.getLatestDBVersion();
+ return migrations.stream()
+ .filter(mig -> isMigrationVersionGreaterThanLatestVersion(latestDBVersion, mig))
+ .collect(Collectors.toList());
+ }
+
+ private boolean isMigrationVersionGreaterThanLatestVersion(DBVersion latestDBVersion, Migration mig) {
+ return mig.getVersion().compareTo(latestDBVersion) > 0;
+ }
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/service/SdcRepoService.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/service/SdcRepoService.java
new file mode 100644
index 0000000000..2888ecb474
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/service/SdcRepoService.java
@@ -0,0 +1,34 @@
+package org.openecomp.sdc.asdctool.migration.service;
+
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.be.dao.cassandra.MigrationTasksDao;
+import org.openecomp.sdc.be.resources.data.MigrationTaskEntry;
+
+import java.math.BigInteger;
+
+public class SdcRepoService {
+
+ private MigrationTasksDao migrationTasksDao;
+
+ public SdcRepoService(MigrationTasksDao migrationTasksDao) {
+ this.migrationTasksDao = migrationTasksDao;
+ }
+
+ public DBVersion getLatestDBVersion() {
+ BigInteger currentMajorVersion = DBVersion.CURRENT_VERSION.getMajor();
+ BigInteger latestMinorVersion = migrationTasksDao.getLatestMinorVersion(currentMajorVersion);
+ return latestMinorVersion == null ? DBVersion.from(currentMajorVersion, BigInteger.valueOf(Integer.MIN_VALUE)) : DBVersion.from(currentMajorVersion, latestMinorVersion);
+ }
+
+ public void clearTasksForCurrentMajor() {
+ BigInteger currentMajorVersion = DBVersion.CURRENT_VERSION.getMajor();
+ migrationTasksDao.deleteAllTasksForVersion(currentMajorVersion);
+ }
+
+ public void createMigrationTask(MigrationTaskEntry migrationTaskEntry) {
+ migrationTasksDao.createMigrationTask(migrationTaskEntry);
+ }
+
+
+
+}
diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/ExampleMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/ExampleMigration.java
new file mode 100644
index 0000000000..1302dc26a8
--- /dev/null
+++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1710/ExampleMigration.java
@@ -0,0 +1,27 @@
+//package org.openecomp.sdc.asdctool.migration.tasks.mig1710;//package org.openecomp.sdc.migration.tasks.mig1710;
+//
+//import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+//import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+//import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+//import org.springframework.stereotype.Component;
+//
+//@Component
+//public class ExampleMigration implements Migration {
+//
+// @Override
+// public String description() {
+// return "some description";
+// }
+//
+// @Override
+// public DBVersion getVersion() {
+// return DBVersion.fromString("1710.0");
+// }
+//
+// @Override
+// public MigrationResult migrate() {
+// MigrationResult migrationResult = new MigrationResult();
+// migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.COMPLETED);
+// return migrationResult;
+// }
+//} \ No newline at end of file
diff --git a/asdctool/src/main/resources/config/configuration.yaml b/asdctool/src/main/resources/config/configuration.yaml
index b998e2cf1f..0421d656be 100644
--- a/asdctool/src/main/resources/config/configuration.yaml
+++ b/asdctool/src/main/resources/config/configuration.yaml
@@ -507,6 +507,7 @@ cassandraConfig:
- { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- { name: sdccomponent, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+ - { name: sdcrepository, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
switchoverDetector:
diff --git a/asdctool/src/main/resources/config/logback.xml b/asdctool/src/main/resources/config/logback.xml
index 0426a32d9e..dadc5254a5 100644
--- a/asdctool/src/main/resources/config/logback.xml
+++ b/asdctool/src/main/resources/config/logback.xml
@@ -4,7 +4,16 @@
<property scope="system" name="ECOMP-subcomponent-name" value="SDC-TOOL" />
<property name="default-log-pattern"
value="%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%X{uuid}|%X{serviceInstanceID}|%thread||${ECOMP-subcomponent-name}|%X{userId}|%level|%X{alarmSeverity}|%X{localAddr}|${beFqdn}|%X{remoteAddr}|%logger{35}|%X{timer}|ActivityType=&lt;%M&gt;, Desc=&lt;%msg&gt;%n" />
-
+
+
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <layout class="ch.qos.logback.classic.PatternLayout">
+ <encoder>
+ <pattern>${default-log-pattern}</pattern>
+ </encoder>
+ </layout>
+ </appender>
+
<appender name="DEBUG_ROLLING"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${HOME}/asdctool/logs/${ECOMP-component-name}/${ECOMP-subcomponent-name}/debug.log</file>
@@ -65,4 +74,8 @@
<appender-ref ref="MALFORMED_DATA"/>
</logger>
+ <logger name="org.openecomp.sdc.asdctool.migration" level="INFO" >
+ <appender-ref ref="STDOUT"/>
+ </logger>
+
</configuration> \ No newline at end of file
diff --git a/asdctool/src/main/resources/scripts/postMigration1707Fix.sh b/asdctool/src/main/resources/scripts/postMigration1707Fix.sh
new file mode 100644
index 0000000000..56a16db70a
--- /dev/null
+++ b/asdctool/src/main/resources/scripts/postMigration1707Fix.sh
@@ -0,0 +1,35 @@
+#!/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 fix-missing-info-1707 $@"
+echo $command
+
+$command
+result=$?
+
+
+
+echo "***********************************"
+echo "***** $result *********************"
+echo "***********************************"
+
+exit $result
+
+
diff --git a/asdctool/src/main/resources/scripts/sdc-migration.sh b/asdctool/src/main/resources/scripts/sdc-migration.sh
new file mode 100644
index 0000000000..1616890217
--- /dev/null
+++ b/asdctool/src/main/resources/scripts/sdc-migration.sh
@@ -0,0 +1,36 @@
+#!/bin/bash
+
+##############################
+# Data Migration
+##############################
+
+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.migration.main.MigrationMenu"
+
+command="java $JVM_LOG_FILE -Xmx6000M -cp $JARS $mainClass $@"
+echo $command
+
+$command
+result=$?
+
+
+
+echo "***********************************"
+echo "***** $result *********************"
+echo "***********************************"
+
+exit $result
+
+
+
diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/DummyMigrationFactory.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/DummyMigrationFactory.java
new file mode 100644
index 0000000000..b16951ef02
--- /dev/null
+++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/DummyMigrationFactory.java
@@ -0,0 +1,72 @@
+package org.openecomp.sdc.asdctool.migration;
+
+
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+
+public class DummyMigrationFactory {
+
+ public static Migration SUCCESSFUL_MIGRATION = new Migration() {
+ @Override
+ public String description() {
+ return "success mig";
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.fromString("1710.22");
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ MigrationResult migrationResult = new MigrationResult();
+ migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.COMPLETED);
+ migrationResult.setMsg("myMsg");
+ return migrationResult;
+ }
+ };
+
+ public static Migration FAILED_MIGRATION = new Migration() {
+ @Override
+ public String description() {
+ return "failed mig";
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.fromString("1710.22");
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ MigrationResult migrationResult = new MigrationResult();
+ migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.FAILED);
+ migrationResult.setMsg("myMsg");
+ return migrationResult;
+ }
+ };
+
+ public static Migration getMigration(String version, MigrationResult.MigrationStatus status) {
+ return new Migration() {
+ @Override
+ public String description() {
+ return "success mig";
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.fromString(version);
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ MigrationResult migrationResult = new MigrationResult();
+ migrationResult.setMigrationStatus(status);
+ migrationResult.setMsg("myMsg");
+ return migrationResult;
+ }
+ };
+ }
+
+}
diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/core/DBVersionTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/core/DBVersionTest.java
new file mode 100644
index 0000000000..4e5fd3ab31
--- /dev/null
+++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/core/DBVersionTest.java
@@ -0,0 +1,57 @@
+package org.openecomp.sdc.asdctool.migration.core;
+
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+
+public class DBVersionTest {
+
+
+ @DataProvider(name = "invalidVersionStringsProvider")
+ private Object[][] invalidVersionStringsProvider() {
+ return new Object[][] {
+ {"1.1.1"},
+ {"1.a"},
+ {"a.1"},
+ {"1"}
+ };
+ }
+
+ @Test(dataProvider = "invalidVersionStringsProvider", expectedExceptions = MigrationException.class)
+ public void testFromString_invalidVersionString(String invalidVersion) {
+ DBVersion.fromString(invalidVersion);
+ }
+
+ @DataProvider(name = "validVersionStringsProvider")
+ private Object[][] validVersionStringsProvider() {
+ return new Object[][] {
+ {"1.1", "1.1"},
+ {"10100.0001", "10100.1"},
+ {"000.1", "0.1"},
+ {"01.00001000", "1.1000"},
+ };
+ }
+
+ @Test(dataProvider = "validVersionStringsProvider")
+ public void testFromString(String validString, String expectedVersionString) {
+ assertEquals(expectedVersionString, DBVersion.fromString(validString).toString());
+ }
+
+ @DataProvider(name = "versionComparisionProvider")
+ public static Object[][] versionComparisionProvider() {
+ return new Object[][] {
+ {"1.1", "001.00001", 0},
+ {"10.1", "0010.00001", 0},
+ {"1.1", "001.000010", -1},
+ {"1.1", "0010.00001", -1},
+ {"10.10", "0010.00001", 1},
+ {"1.1", "001.00", 1},
+ };
+ }
+
+ @Test(dataProvider = "versionComparisionProvider")
+ public void testVersionCompareTo2(String firstVersion, String otherVersion, int expectedComparisionResult) throws Exception {
+ assertEquals(DBVersion.fromString(firstVersion).compareTo(DBVersion.fromString(otherVersion)), expectedComparisionResult);
+ }
+}
diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/core/SdcMigrationToolTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/core/SdcMigrationToolTest.java
new file mode 100644
index 0000000000..b1813227e2
--- /dev/null
+++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/core/SdcMigrationToolTest.java
@@ -0,0 +1,101 @@
+package org.openecomp.sdc.asdctool.migration.core;
+
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.mockito.internal.verification.Times;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+import org.openecomp.sdc.asdctool.migration.resolver.MigrationResolver;
+import org.openecomp.sdc.asdctool.migration.service.SdcRepoService;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class SdcMigrationToolTest {
+
+ @InjectMocks
+ private SdcMigrationTool testInstance = spy(SdcMigrationTool.class);
+
+ @Mock
+ private MigrationResolver migrationResolverMock;
+
+ @Mock
+ private SdcRepoService sdcRepoServiceMock;
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void testMigrate_noMigrations() throws Exception {
+ when(migrationResolverMock.resolveMigrations()).thenReturn(Collections.emptyList());
+ testInstance.migrate(false);
+ verify(sdcRepoServiceMock, new Times(0)).clearTasksForCurrentMajor();
+ verify(sdcRepoServiceMock, new Times(0)).createMigrationTask(Mockito.any());
+ }
+
+ @Test
+ public void testMigrate_enforceFlag_removeAllMigrationTasksForCurrentVersion() throws Exception {
+ when(migrationResolverMock.resolveMigrations()).thenReturn(Collections.emptyList());
+ testInstance.migrate(true);
+ verify(sdcRepoServiceMock, new Times(1)).clearTasksForCurrentMajor();
+ }
+
+ @Test
+ public void testMigrate_stopAfterFirstFailure() throws Exception {
+ when(migrationResolverMock.resolveMigrations()).thenReturn(Arrays.asList(new SuccessfulMigration(), new FailedMigration(), new SuccessfulMigration()));
+ testInstance.migrate(false);
+ verify(sdcRepoServiceMock, new Times(0)).clearTasksForCurrentMajor();
+ verify(sdcRepoServiceMock, new Times(1)).createMigrationTask(Mockito.any());
+
+ }
+
+ private class FailedMigration implements Migration {
+
+ @Override
+ public String description() {
+ return null;
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.fromString("1710.22");
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ MigrationResult migrationResult = new MigrationResult();
+ migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.FAILED);
+ return migrationResult;
+ }
+ }
+
+ private class SuccessfulMigration implements Migration {
+
+ @Override
+ public String description() {
+ return null;
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.fromString("1710.22");
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ MigrationResult migrationResult = new MigrationResult();
+ migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.COMPLETED);
+ return migrationResult;
+ }
+ }
+}
diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutorImplTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutorImplTest.java
new file mode 100644
index 0000000000..763d6c83d2
--- /dev/null
+++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/core/execution/MigrationExecutorImplTest.java
@@ -0,0 +1,47 @@
+package org.openecomp.sdc.asdctool.migration.core.execution;
+
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+
+public class MigrationExecutorImplTest {
+
+ @Test
+ public void testExecuteMigration() throws Exception {
+ MigrationExecutionResult execute = new MigrationExecutorImpl().execute(new DummyMigration());
+
+ }
+
+ private void assertMigrationTaskEntryByMigrationExecutionResult(MigrationExecutionResult executionResult, Migration migration, MigrationResult result) {
+ assertEquals(executionResult.getMsg(), result.getMsg());
+ assertEquals(executionResult.getMigrationStatus().name(), result.getMigrationStatus());
+ assertEquals(executionResult.getTaskName(), migration.getClass().getName());
+ assertEquals(executionResult.getVersion(), migration.getVersion());
+ assertNotNull(executionResult.getExecutionTime());
+ }
+
+ private class DummyMigration implements Migration {
+
+ @Override
+ public String description() {
+ return null;
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.fromString("1710.22");
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ MigrationResult migrationResult = new MigrationResult();
+ migrationResult.setMigrationStatus(MigrationResult.MigrationStatus.COMPLETED);
+ migrationResult.setMsg("myMsg");
+ return migrationResult;
+ }
+ }
+}
diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/resolver/SpringBeansMigrationResolverTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/resolver/SpringBeansMigrationResolverTest.java
new file mode 100644
index 0000000000..6084608f0e
--- /dev/null
+++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/resolver/SpringBeansMigrationResolverTest.java
@@ -0,0 +1,84 @@
+package org.openecomp.sdc.asdctool.migration.resolver;
+
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
+import org.openecomp.sdc.asdctool.migration.service.SdcRepoService;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+public class SpringBeansMigrationResolverTest {
+
+ @InjectMocks
+ private SpringBeansMigrationResolver testInstance;
+
+ @Mock
+ private SdcRepoService sdcRepoServiceMock;
+
+ private List<Migration> migrations = Arrays.asList(createMigration("1710.1"), createMigration("1710.22"), createMigration("1707.12"), createMigration("1710.3"));
+
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ testInstance.setMigrations(migrations);
+ }
+
+ @Test
+ public void testResolveMigrations_getMigrationsWithVersionGreaterThanLatest() throws Exception {
+ when(sdcRepoServiceMock.getLatestDBVersion()).thenReturn(DBVersion.fromString("1710.2"));
+ List<Migration> resolvedMigrations = testInstance.resolveMigrations();
+ assertEquals(resolvedMigrations.size(), 2);
+ assertEquals(resolvedMigrations.get(0).getVersion(), DBVersion.fromString("1710.3"));
+ assertEquals(resolvedMigrations.get(1).getVersion(), DBVersion.fromString("1710.22"));
+ }
+
+ @Test
+ public void testResolveMigration_noLatestVersionForCurrentMajorVersion() throws Exception {
+ when(sdcRepoServiceMock.getLatestDBVersion()).thenReturn(DBVersion.fromString("1710.-1"));
+ List<Migration> resolvedMigrations = testInstance.resolveMigrations();
+ assertEquals(resolvedMigrations.size(), 3);
+ assertEquals(resolvedMigrations.get(0).getVersion(), DBVersion.fromString("1710.1"));
+ assertEquals(resolvedMigrations.get(1).getVersion(), DBVersion.fromString("1710.3"));
+ assertEquals(resolvedMigrations.get(2).getVersion(), DBVersion.fromString("1710.22"));
+ }
+
+ @Test
+ public void testResolveMigrations_emptyMigrationsList() throws Exception {
+ testInstance.setMigrations(Collections.emptyList());
+ when(sdcRepoServiceMock.getLatestDBVersion()).thenReturn(DBVersion.fromString("1710.-1"));
+ List<Migration> resolvedMigrations = testInstance.resolveMigrations();
+ assertTrue(resolvedMigrations.isEmpty());
+ }
+
+ private Migration createMigration(String version) {
+ return new Migration() {
+ @Override
+ public String description() {
+ return null;
+ }
+
+ @Override
+ public DBVersion getVersion() {
+ return DBVersion.fromString(version);
+ }
+
+ @Override
+ public MigrationResult migrate() {
+ return null;
+ }
+ };
+ }
+
+}
diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/scanner/ClassScanner.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/scanner/ClassScanner.java
new file mode 100644
index 0000000000..a2bf623b83
--- /dev/null
+++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/scanner/ClassScanner.java
@@ -0,0 +1,81 @@
+package org.openecomp.sdc.asdctool.migration.scanner;
+
+import org.apache.commons.io.FileUtils;
+import org.openecomp.sdc.asdctool.migration.core.MigrationException;
+
+import java.io.File;
+import java.lang.reflect.Modifier;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+
+/**
+ * scan and instantiate classes of given type in the class path
+ */
+public class ClassScanner {
+
+
+ private ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+
+ public <T> List<T> getAllClassesOfType(String basePackage, Class<T> ofType) {
+ Collection<File> allClassesInPackage = getAllClassesInPackage(basePackage);
+ List<T> loadedClasses = new ArrayList<>();
+ for (File clazzFile : allClassesInPackage) {
+ Optional<T> instance = loadAndInstantiateClass(getClassReference(clazzFile), ofType);
+ instance.ifPresent(loadedClasses::add);
+ }
+ return loadedClasses;
+ }
+
+ private <T> Optional<T> loadAndInstantiateClass(String classReference, Class<T> ofType) {
+ try {
+ return instantiateClassOfType(classReference, ofType);
+ }catch (ClassNotFoundException e) {
+ //log
+ throw new MigrationException(String.format("could not find class %s of type %s. cause: %s", classReference, ofType.toGenericString(), e.getMessage()));
+ } catch (IllegalAccessException e1) {
+ //log
+ throw new MigrationException(String.format("could not instantiate class %s of type %s. class is not accessible. cause: %s", classReference, ofType.toGenericString(), e1.getMessage()));
+ } catch (InstantiationException e2) {
+ //log
+ throw new MigrationException(String.format("could not instantiate class %s of type %s. cause: %s", classReference, ofType.toGenericString(), e2.getMessage()));
+ }
+ }
+
+ private <T> Optional<T> instantiateClassOfType(String classReference, Class<T> ofType) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
+ String className = classReference.replaceAll(".class$", "").replaceAll(".class", "");
+ Class<?> aClass = classLoader.loadClass(className);
+ if (ofType.isAssignableFrom(aClass) && isInstantiateAbleClass(aClass)){
+ return Optional.of((T) aClass.newInstance());
+ }
+ return Optional.empty();
+ }
+
+ private boolean isInstantiateAbleClass(Class<?> clazz) {
+ return !Modifier.isAbstract(clazz.getModifiers()) && !clazz.isEnum() && !clazz.isAnonymousClass() && !clazz.isInterface();
+ }
+
+ private Collection<File> getAllClassesInPackage(String fromPackage) {
+ String path = fromPackage.replace(".", "/");
+ URL resource = classLoader.getResource(path);
+ if (noMigrationTasks(resource)) {
+ return Collections.emptyList();
+ }
+ return FileUtils.listFiles(new File(resource.getFile()), new String[]{"class"}, true);
+ }
+
+ private boolean noMigrationTasks(URL resource) {
+ return resource == null;
+ }
+
+ private String getClassReference(File classFile) {
+ String asPackage = classFile.getPath().replace(File.separator, ".");
+ String classes = "classes.";
+ return asPackage.substring(asPackage.indexOf(classes) + classes.length());
+ }
+
+
+}
diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/service/SdcRepoServiceTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/service/SdcRepoServiceTest.java
new file mode 100644
index 0000000000..f8e9abe2c9
--- /dev/null
+++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/service/SdcRepoServiceTest.java
@@ -0,0 +1,55 @@
+package org.openecomp.sdc.asdctool.migration.service;
+
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.internal.verification.Times;
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.be.dao.cassandra.MigrationTasksDao;
+import org.openecomp.sdc.be.resources.data.MigrationTaskEntry;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.math.BigInteger;
+
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertEquals;
+
+public class SdcRepoServiceTest {
+
+ @InjectMocks
+ private SdcRepoService testInstance;
+
+ @Mock
+ private MigrationTasksDao migrationTasksDaoMock;
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void testGetLatestVersion_noMinorVersionForCurrentVersion() throws Exception {
+ when(migrationTasksDaoMock.getLatestMinorVersion(DBVersion.CURRENT_VERSION.getMajor())).thenReturn(null);
+ DBVersion latestDBVersion = testInstance.getLatestDBVersion();
+ assertEquals(latestDBVersion.getMajor(), DBVersion.CURRENT_VERSION.getMajor());
+ assertEquals(latestDBVersion.getMinor(), BigInteger.valueOf(Integer.MIN_VALUE));
+ }
+
+ @Test
+ public void testGetLatestVersion() throws Exception {
+ when(migrationTasksDaoMock.getLatestMinorVersion(DBVersion.CURRENT_VERSION.getMajor())).thenReturn(BigInteger.TEN);
+ DBVersion latestDBVersion = testInstance.getLatestDBVersion();
+ assertEquals(latestDBVersion.getMajor(), DBVersion.CURRENT_VERSION.getMajor());
+ assertEquals(latestDBVersion.getMinor(), BigInteger.TEN);
+ }
+
+ @Test
+ public void testCreateMigrationTask() throws Exception {
+ MigrationTaskEntry taskEntry = new MigrationTaskEntry();
+ testInstance.createMigrationTask(taskEntry);
+ verify(migrationTasksDaoMock, new Times(1)).createMigrationTask(taskEntry);
+ }
+
+}
diff --git a/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/task/MigrationTasksTest.java b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/task/MigrationTasksTest.java
new file mode 100644
index 0000000000..037d51ba12
--- /dev/null
+++ b/asdctool/src/test/java/org/openecomp/sdc/asdctool/migration/task/MigrationTasksTest.java
@@ -0,0 +1,56 @@
+package org.openecomp.sdc.asdctool.migration.task;
+
+import org.apache.commons.lang.StringUtils;
+import org.openecomp.sdc.asdctool.migration.core.DBVersion;
+import org.openecomp.sdc.asdctool.migration.core.task.Migration;
+import org.openecomp.sdc.asdctool.migration.scanner.ClassScanner;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+
+public class MigrationTasksTest {
+
+ public static final String MIGRATIONS_BASE_PACKAGE = "org.openecomp.sdc.asdctool.migration.tasks";
+ private List<Migration> migrations;
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ ClassScanner classScanner = new ClassScanner();
+ migrations = classScanner.getAllClassesOfType(MIGRATIONS_BASE_PACKAGE, Migration.class);
+ }
+
+ @Test
+ public void testNoTasksWithSameVersion() throws Exception {
+ Map<DBVersion, List<Migration>> migrationsByVersion = migrations.stream().collect(Collectors.groupingBy(Migration::getVersion));
+ migrationsByVersion.forEach((version, migrations) -> {
+ if (migrations.size() > 1) {
+ System.out.println(String.format("the following migration tasks have the same version %s. versions must be unique", version.toString()));
+ Assert.fail(String.format("migration tasks %s has same version %s. migration tasks versions must be unique.", getMigrationsNameAsString(migrations), version.toString()));
+ }
+ });
+ }
+
+ @Test
+ public void testNoTaskWithVersionGreaterThanCurrentVersion() throws Exception {
+ Set<Migration> migrationsWithVersionsGreaterThanCurrent = migrations.stream().filter(mig -> mig.getVersion().compareTo(DBVersion.CURRENT_VERSION) > 0)
+ .collect(Collectors.toSet());
+
+ if (!migrationsWithVersionsGreaterThanCurrent.isEmpty()) {
+ Assert.fail(String.format("migrations tasks %s have version which is greater than DBVersion.CURRENT_VERSION %s. did you forget to update current version?",
+ getMigrationsNameAsString(migrationsWithVersionsGreaterThanCurrent),
+ DBVersion.CURRENT_VERSION.toString()));
+ }
+ }
+
+ private String getMigrationsNameAsString(Collection<Migration> migrations) {
+ return StringUtils.join(migrations.stream().map(mig -> mig.getClass().getName()).collect(Collectors.toList()), ",");
+ }
+}
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 cec045d8a3..ebdfe22185 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
@@ -340,10 +340,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
boolean needGenerate;
needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
- needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()));
+ needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
return needGenerate;
}
+ private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
+ return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
+ }
+
public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
@@ -798,13 +802,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(artifactResult.left().value());
}
- private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
+ private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
String artifactId = null;
// step 11
- Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
+ Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
if (payloadEither.isRight()) {
return Either.right(payloadEither.right().value());
}
@@ -814,14 +818,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (shouldLock) {
Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
if (lockComponent.isRight()) {
- handleAuditing(auditingAction, parent, parentId, user, null, null, null, lockComponent.right().value(), componentType, null);
+ handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null);
return Either.right(lockComponent.right().value());
}
}
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
try {
- resultOp = createArtifact(parent, parentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
+ resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
return resultOp;
} finally {
if (shouldLock) {
@@ -872,28 +876,28 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
}
- private Either<byte[], ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
+ private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) {
// Md5 validations
Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
if (validateMd5.isRight()) {
ResponseFormat responseFormat = validateMd5.right().value();
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(responseFormat);
}
// step 11
- Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(parentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
+ Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
if (validateResult.isRight()) {
ResponseFormat responseFormat = validateResult.right().value();
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
return Either.right(validateResult.right().value());
}
Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
if (payloadEither.isRight()) {
ResponseFormat responseFormat = payloadEither.right().value();
- handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
+ handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
log.debug("Error during handle payload");
return Either.right(responseFormat);
}
@@ -903,7 +907,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType());
if (validateAndConvertHeatParamers.isRight()) {
ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
- handleAuditing(auditingAction, parent, parentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
+ handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
log.debug("Error during handle payload");
return Either.right(responseFormat);
}
@@ -1025,9 +1029,16 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(true);
}
- private Either<ArtifactDefinition, ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
+ private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
+ Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
+ if (artifactById.isRight()) {
+ return Either.right(artifactById.right().value());
+ }
+ ArtifactDefinition currentArtifactInfo = artifactById.left().value();
+
+ ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
if (validateInformationalArtifactRes.isRight()) {
return Either.right(validateInformationalArtifactRes.right().value());
@@ -1036,16 +1047,11 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (validateAndSetArtifactname.isRight()) {
return Either.right(validateAndSetArtifactname.right().value());
}
- Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, parentId, operation, artifactId);
- if (artifactById.isRight()) {
- return Either.right(artifactById.right().value());
- }
- ArtifactDefinition currentArtifactInfo = artifactById.left().value();
if (operationName != null && interfaceName != null) {
operationName = operationName.toLowerCase();
interfaceName = interfaceName.toLowerCase();
}
- Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(parentId, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType, inTransaction);
+ Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType);
if (logicalNameStatus.isRight()) {
return Either.right(logicalNameStatus.right().value());
}
@@ -1058,7 +1064,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
}
- composeArtifactId(parentId, artifactId, artifactInfo, interfaceName, operationName);
+ composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
if (currentArtifactInfo != null) {
artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
}
@@ -1077,7 +1083,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
boolean isCreate = operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create;
if (isDeploymentArtifact(artifactInfo)) {
- Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, parentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
+ Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
if (deploymentValidationResult.isRight()) {
return Either.right(deploymentValidationResult.right().value());
}
@@ -1135,6 +1141,14 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(artifactInfo);
}
+ private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
+ if(operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.Update)){
+ artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
+ artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
+ artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
+ }
+ }
+
private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
Either<ArtifactDefinition, ResponseFormat> result = null;
@@ -1474,13 +1488,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
if (fetchedArtifact != null) {
log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
- fetchedArtifact.setEsId("");
- fetchedArtifact.setArtifactName("");
- fetchedArtifact.setDescription("");
- fetchedArtifact.setApiUrl("");
- fetchedArtifact.setArtifactChecksum("");
+ fetchedArtifact.setEsId(null);
+ fetchedArtifact.setArtifactName(null);
+ fetchedArtifact.setDescription(null);
+ fetchedArtifact.setApiUrl(null);
+ fetchedArtifact.setArtifactChecksum(null);
nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
- fetchedArtifact.setArtifactUUID("");
+ fetchedArtifact.setArtifactUUID(null);
long time = System.currentTimeMillis();
fetchedArtifact.setPayloadUpdateDate(time);
fetchedArtifact.setHeatParameters(null);
@@ -1540,10 +1554,10 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
return Either.left(currentArtifactInfo);
}
- private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
- ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType, boolean inTransaction) {
- String artifactLabel = artifactInfo.getArtifactLabel();
+ private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
+ ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType) {
+ String artifactLabel = artifactInfo.getArtifactLabel();
if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
log.debug("missing artifact logical name for component {}", componentId);
@@ -1584,27 +1598,25 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
}
- if (!validateLabelUniqueness(componentId, artifactLabel, componentType)) {
+ if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
log.debug("Non unique Artifact label : {}", artifactLabel);
return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
}
}
artifactInfo.setArtifactLabel(artifactLabel);
- if (currentArtifactInfo != null && !currentArtifactInfo.getArtifactLabel().equals(artifactInfo.getArtifactLabel())) {
- log.info("Logical artifact's name cannot be changed {}", artifactId);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
- }
return Either.left(ActionStatus.OK);
}
- private boolean validateLabelUniqueness(String parentId, String artifactLabel, ComponentTypeEnum componentType) {
+ private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
boolean isUnique = true;
- if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
+ if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
+ artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
} else {
+ artifacts = artifactToscaOperation.getArtifacts(componentId);
}
- // Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, inTransaction);
- Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactToscaOperation.getArtifacts(parentId);
+
if (artifacts.isLeft()) {
for (String label : artifacts.left().value().keySet()) {
if (label.equals(artifactLabel)) {
@@ -1614,7 +1626,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
}
if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
- Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true, true);
+ Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(componentId, true, true);
if (allInterfacesOfResource.isLeft()) {
for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
for (Operation operation : interace.getOperationsMap().values()) {
@@ -3886,7 +3898,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
* currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
*/
String currentHeatId = currHeatArtifact.getUniqueId();
-
+
String esArtifactId = currHeatArtifact.getEsId();
Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
if (artifactfromES.isRight()) {
@@ -3899,8 +3911,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
ESArtifactData esArtifactData = artifactfromES.left().value();
byte[] data = esArtifactData.getDataAsArray();
-
-
+
+
ArtifactDefinition updatedHeatArt = currHeatArtifact;
List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
@@ -3949,7 +3961,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null)
esArtifactData.setId(updatedHeatArt.getEsId());
res = saveArtifacts(esArtifactData, parent.getUniqueId(), false);
-
+
if (res) {
log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
@@ -3964,7 +3976,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
resultOp = Either.right(responseFormat);
// return resultOp;
}
-
+
insideEither = Either.left(updatedHeatArt);
}
}
@@ -3976,13 +3988,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
}
- if ( needToUpdateGroup && updateHeatEnvArtifact.isLeft() ){
+ if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent, componentType);
- if ( result != ActionStatus.OK ){
+ if (result != ActionStatus.OK) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
return Either.right(responseFormat);
}
}
+
+ if (updatedHeatEnvParams.isEmpty()) {
+ return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, artifactId, componentType);
+ }
resultOp = Either.left(insideEither);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
@@ -3990,6 +4006,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
}
+ private Either<Either<ArtifactDefinition,Operation>,ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, String uniqueId, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML);
+ handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
+ return Either.right(responseFormat);
+ }
+
+
private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
StorageOperationStatus error = StorageOperationStatus.OK;
log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
@@ -4092,7 +4115,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
if (errorWrapper.isEmpty()) {
auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
- downloadedArtifact = downloadArtifact(component.getDeploymentArtifacts(), artifactUUID, errorWrapper, component.getName());
+ downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
}
if (errorWrapper.isEmpty()) {
result = Either.left(downloadedArtifact);
@@ -4733,17 +4756,17 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic {
byte[] downloadedArtifact = null;
Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
- List<ArtifactDefinition> deploymentArtifacts = null;
+ List<ArtifactDefinition> artifactsList = null;
ArtifactDefinition deploymentArtifact = null;
if (artifacts != null && !artifacts.isEmpty()) {
- deploymentArtifacts = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
+ artifactsList = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
}
- if (deploymentArtifacts == null || deploymentArtifacts.isEmpty()) {
+ if (artifactsList == null || artifactsList.isEmpty()) {
log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
}
if (errorWrapper.isEmpty()) {
- deploymentArtifact = deploymentArtifacts.get(0);
+ deploymentArtifact = artifactsList.get(0);
downloadArtifactEither = downloadArtifact(deploymentArtifact);
if (downloadArtifactEither.isRight()) {
log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
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 df8460ca96..1d153e0a5d 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
@@ -47,6 +47,7 @@ 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.cache.ApplicationDataTypeCache;
@@ -391,11 +392,10 @@ public abstract class BaseBusinessLogic {
}
protected Either<Boolean, ResponseFormat> validatePropertyDefaultValue(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) {
- log.debug("validate property");
String type = null;
String innerType = null;
if (!propertyOperation.isPropertyTypeValid(property)) {
- log.info("Invalid type for property");
+ log.info("Invalid type for property {} type {}", property.getName(), property.getType());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, property.getType(), property.getName());
return Either.right(responseFormat);
}
@@ -404,13 +404,13 @@ public abstract class BaseBusinessLogic {
ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes);
innerType = propertyInnerTypeValid.getLeft();
if (!propertyInnerTypeValid.getRight().booleanValue()) {
- log.info("Invalid inner type for property");
+ log.info("Invalid inner type for property {} type {}", property.getName(), property.getType() );
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName());
return Either.right(responseFormat);
}
}
if (!propertyOperation.isPropertyDefaultValueValid(property, dataTypes)) {
- log.info("Invalid default value for property");
+ log.info("Invalid default value for property {} type {}", property.getName(), property.getType() );
ResponseFormat responseFormat;
if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) {
responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue());
@@ -568,7 +568,7 @@ public abstract class BaseBusinessLogic {
return Arrays.asList(enumValues).contains(enumFound);
}
- protected Either<String, StorageOperationStatus> validatePropValueBeforeCreate(ComponentInstanceProperty property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
+ protected Either<String, StorageOperationStatus> validatePropValueBeforeCreate(IPropertyInputCommon property, String value, boolean isValidate, String innerType, Map<String, DataTypeDefinition> allDataTypes) {
String propertyType = property.getType();
ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
@@ -603,7 +603,7 @@ public abstract class BaseBusinessLogic {
}
ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, property.getRules(), innerType, allDataTypes, isValidate);
- log.debug("After validateAndUpdateRules. pair = {}", pair);
+ log.trace("After validateAndUpdateRules. pair = {}", pair);
if (pair.getRight() != null && pair.getRight() == false) {
BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java
new file mode 100644
index 0000000000..237ec6d5fe
--- /dev/null
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/CassandraHealthCheck.java
@@ -0,0 +1,189 @@
+package org.openecomp.sdc.be.components.impl;
+
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+
+import javax.annotation.PostConstruct;
+
+import org.openecomp.sdc.be.config.ConfigurationManager;
+import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils;
+import org.openecomp.sdc.be.dao.cassandra.schema.Table;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+import com.datastax.driver.core.Session;
+
+@Component("cassandra-health-check")
+public class CassandraHealthCheck {
+
+
+ private static Logger log = LoggerFactory.getLogger(CassandraHealthCheck.class.getName());
+
+ private String localDataCenterName = null;
+
+ private Set<String> sdcKeyspaces = new HashSet<String>();
+
+ private int HC_FormulaNumber;
+
+ @PostConstruct
+ private void init() {
+
+ //Initialize local data center name - this field must be filled by DevOps
+ localDataCenterName = ConfigurationManager.getConfigurationManager().getConfiguration().getCassandraConfig().getLocalDataCenter();
+
+ if (GeneralUtility.isEmptyString(localDataCenterName)) {
+ log.error("localDataCenter Name in configuration.yaml is missing.");
+ return;
+ }
+
+ //Collect all SDC keyspaces
+ for (Table table : Table.values()) {
+ sdcKeyspaces.add(table.getTableDescription().getKeyspace());
+ }
+
+ String titanCfgFile = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanCfgFile();
+ Properties prop = new Properties();
+ InputStream titanProp = null;
+ try {
+ //load a properties file
+ titanProp = new FileInputStream(titanCfgFile);
+ prop.load(titanProp);
+ //Add titan keyspace
+ String titanKeyspace = prop.getProperty("storage.cassandra.keyspace");
+ if (!GeneralUtility.isEmptyString(titanKeyspace)) {
+ sdcKeyspaces.add(titanKeyspace);
+ }
+ } catch (Exception e) {
+ log.error("Failed to open titen.properties file , url is : {}", titanCfgFile);
+ }
+
+ log.info("All sdc keyspaces are : {}", sdcKeyspaces);
+
+ //Calculate the Formula of Health Check
+ Cluster cluster = null;
+ try {
+
+ log.info("creating cluster for Cassandra Health Check.");
+ //Create cluster from nodes in cassandra configuration
+ cluster = SdcSchemaUtils.createCluster();
+ if (cluster == null) {
+ log.error("Failure create cassandra cluster.");
+ return;
+ }
+
+ Metadata metadata = cluster.getMetadata();
+
+ if (metadata == null) {
+ log.error("Failure get cassandra metadata.");
+ return;
+ }
+
+ log.info("Cluster Metadata: {}", metadata.toString());
+ List<KeyspaceMetadata> keyspaces = metadata.getKeyspaces();
+ List<Integer> replactionFactorList = new ArrayList<Integer>();
+
+ //Collect the keyspaces Replication Factor of current localDataCenter
+ for (KeyspaceMetadata keyspace : keyspaces) {
+
+ if (sdcKeyspaces.contains(keyspace.getName())) {
+
+ log.info("keyspace : {} , replication: {}", keyspace.getName(), keyspace.getReplication());
+ Map<String, String> replicationOptions = keyspace.getReplication();
+
+ //In 1 site with one data center
+ if (replicationOptions.containsKey("replication_factor")) {
+ replactionFactorList.add(Integer.parseInt(replicationOptions.get("replication_factor")));
+ }
+ //In multiple sites with some data center
+ else if (replicationOptions.containsKey(localDataCenterName)) {
+ replactionFactorList.add(Integer.parseInt(replicationOptions.get(localDataCenterName)));
+ }
+ }
+ }
+
+ if (replactionFactorList.size() == 0) {
+ log.error("Replication factor NOT found in all keyspaces");
+ return;
+ }
+
+ int maxReplicationFactor = Collections.max(replactionFactorList);
+ log.info("maxReplication Factor is: {}", maxReplicationFactor);
+
+ int localQuorum = maxReplicationFactor/2 + 1;
+ log.info("localQuorum is: {}", localQuorum);
+
+ HC_FormulaNumber = maxReplicationFactor - localQuorum;
+
+ log.info("Health Check formula : Replication Factor – Local_Quorum = {}", HC_FormulaNumber);
+
+
+ } catch (Exception e) {
+ log.error("create cassandra cluster failed with exception.", e);
+ } finally {
+ if (cluster != null) {
+ cluster.close();
+ }
+ }
+
+ }
+
+ public boolean getCassandraStatus() {
+
+ if (GeneralUtility.isEmptyString(localDataCenterName)) {
+ log.error("localDataCenter Name in configuration.yaml is missing.");
+ return false;
+ }
+
+ Cluster cluster = null;
+ Session session = null;
+ try {
+ log.info("creating cluster for Cassandra for monitoring.");
+ cluster = SdcSchemaUtils.createCluster();
+ if (cluster == null) {
+ log.error("Failure create cassandra cluster.");
+ return false;
+ }
+ session = cluster.connect();
+ Metadata metadata = cluster.getMetadata();
+
+ if (metadata == null) {
+ log.error("Failure get cassandra metadata.");
+ return false;
+ }
+
+ log.info("The number of cassandra nodes is:{}", metadata.getAllHosts().size());
+
+ //Count the number of data center nodes that are down
+ Long downHostsNumber = metadata.getAllHosts().stream()
+ .filter(x -> x.getDatacenter().equals(localDataCenterName) && !x.isUp()).count();
+
+ log.info("The cassandra down nodes number is {}", downHostsNumber.toString());
+ return (HC_FormulaNumber >= downHostsNumber);
+
+ } catch (Exception e) {
+ log.error("create cassandra cluster failed with exception.", e);
+ return false;
+ } finally {
+ if (session != null) {
+ session.close();
+ }
+ if (cluster != null) {
+ cluster.close();
+ }
+ }
+ }
+}
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 5ee5c88f69..d1be69689e 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
@@ -183,11 +183,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
return Either.right(errorResponse);
}
- description = ValidationUtils.removeNoneUtf8Chars(description);
- description = ValidationUtils.normaliseWhitespace(description);
- description = ValidationUtils.stripOctets(description);
- description = ValidationUtils.removeHtmlTagsOnly(description);
-
+ description = cleanUpText(description);
Either<Boolean, ResponseFormat> validatDescription = validateComponentDescription(description, type);
if (validatDescription.isRight()) {
ResponseFormat responseFormat = validatDescription.right().value();
@@ -666,19 +662,25 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
toscaArtifact = generateToscaRes.left().value().left().value();
component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact);
- toscaArtifact = component.getToscaArtifacts().values().stream()
- .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()))
- .findAny().get();
- generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, true);
- }
- if (generateToscaRes.isRight()) {
- return generateToscaRes;
+ if(!isAbstractResource(component)){
+ toscaArtifact = component.getToscaArtifacts().values().stream()
+ .filter(p -> p.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()))
+ .findAny().get();
+ generateToscaRes = saveToscaArtifactPayload(toscaArtifact, component, user, isInCertificationRequest, shouldLock, inTransaction, true);
+ if (generateToscaRes.isRight()) {
+ return generateToscaRes;
+ }
+ toscaArtifact = generateToscaRes.left().value().left().value();
+ component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact);
+ }
}
- ArtifactDefinition toscaArtifact = generateToscaRes.left().value().left().value();
- component.getToscaArtifacts().put(toscaArtifact.getArtifactLabel(), toscaArtifact);
return generateToscaRes;
}
+ private boolean isAbstractResource(Component component) {
+ return component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).isAbstract();
+ }
+
public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> saveToscaArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest, boolean shouldLock,
boolean inTransaction, boolean fetchTemplatesFromDB) {
return artifactsBusinessLogic.generateAndSaveToscaArtifact(artifactDefinition, component, user, isInCertificationRequest, shouldLock, inTransaction, fetchTemplatesFromDB);
@@ -735,11 +737,11 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
}
- public Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent, AuditingActionEnum audatingAction) {
+ public Either<Boolean, ResponseFormat> validateAndUpdateDescription(User user, Component currentComponent, Component updatedComponent, AuditingActionEnum auditingAction) {
String descriptionUpdated = updatedComponent.getDescription();
String descriptionCurrent = currentComponent.getDescription();
if (descriptionUpdated != null && !descriptionCurrent.equals(descriptionUpdated)) {
- Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, updatedComponent, audatingAction);
+ Either<Boolean, ResponseFormat> validateDescriptionResponse = validateDescriptionAndCleanup(user, updatedComponent, auditingAction);
if (validateDescriptionResponse.isRight()) {
ResponseFormat errorRespons = validateDescriptionResponse.right().value();
return Either.right(errorRespons);
@@ -977,8 +979,12 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
protected <T extends Component> Either<Resource, ResponseFormat> fetchAndSetDerivedFromGenericType(T component){
-
- String genericTypeToscaName = component.fetchGenericTypeToscaNameFromConfig();
+ String genericTypeToscaName = null;
+ if(component.getComponentType() == ComponentTypeEnum.RESOURCE && ((Resource)component).getResourceType() == ResourceTypeEnum.CVFC){
+ genericTypeToscaName = ((Resource)component).getDerivedFrom().get(0);
+ } else {
+ genericTypeToscaName = component.fetchGenericTypeToscaNameFromConfig();
+ }
if(null == genericTypeToscaName)
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
Either<Resource, StorageOperationStatus> findLatestGeneric = toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(genericTypeToscaName);
@@ -1237,6 +1243,14 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic {
}
return isMatchingType;
}
+
+ protected String cleanUpText(String text){
+ text = ValidationUtils.removeNoneUtf8Chars(text);
+ text = ValidationUtils.normaliseWhitespace(text);
+ text = ValidationUtils.stripOctets(text);
+ text = ValidationUtils.removeHtmlTagsOnly(text);
+ return text;
+ }
}
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 5da416ec0b..56cd91d754 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
@@ -58,10 +58,12 @@ 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.InputDefinition;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+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.IComponentInstanceOperation;
@@ -72,6 +74,7 @@ import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
import org.openecomp.sdc.be.resources.data.PropertyValueData;
+import org.openecomp.sdc.be.tosca.ToscaUtils;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.api.Constants;
@@ -142,9 +145,9 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
containerComponent = validateComponentExists.left().value();
}
- Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances = validateAllowedToContainCompInstances(containerComponent);
- if (validateAllowedToContainCompInstances.isRight()) {
- return Either.right(validateAllowedToContainCompInstances.right().value());
+ if (ToscaUtils.isAtomicType(containerComponent)) {
+ log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
}
Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
@@ -201,9 +204,9 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists.left().value();
- Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances = validateAllowedToContainCompInstances(containerComponent);
- if (validateAllowedToContainCompInstances.isRight()) {
- return Either.right(validateAllowedToContainCompInstances.right().value());
+ if (ToscaUtils.isAtomicType(containerComponent)) {
+ log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
}
Either<Boolean, ResponseFormat> validateCanWorkOnComponent = validateCanWorkOnComponent(containerComponent, userId);
@@ -620,6 +623,7 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
Optional<ComponentInstance> componentInstanceOptional = null;
Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
ComponentInstance oldComponentInstance = null;
+ boolean isNameChanged = false;
if (resultOp == null) {
componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
@@ -631,6 +635,9 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
if (resultOp == null) {
oldComponentInstance = componentInstanceOptional.get();
String newInstanceName = componentInstance.getName();
+ if ( oldComponentInstance!=null && oldComponentInstance.getName() != null
+ && !oldComponentInstance.getName().equals( newInstanceName ) )
+ isNameChanged = true;
Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
if (!isUniqueName) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName);
@@ -643,6 +650,14 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
updateRes.right().value());
resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
+ }else{
+ //region - Update instance Groups
+ if ( isNameChanged ){
+ Either result = toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance( containerComponent ,oldComponentInstance ,componentInstanceId );
+ if ( result.isRight() )
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId ,result.right().value() );
+ }
+ //endregion
}
}
if (resultOp == null) {
@@ -662,11 +677,29 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
return resultOp;
}
+ /**
+ * @param oldPrefix- The normalized old vf name
+ * @param newNormailzedPrefix- The normalized new vf name
+ * @param qualifiedGroupInstanceName- old Group Instance Name
+ **/
+ //modify group names
+ private String getNewGroupName( String oldPrefix ,String newNormailzedPrefix , String qualifiedGroupInstanceName){
+ if (qualifiedGroupInstanceName == null){
+ log.info("CANNOT change group name ");
+ return null;
+ }
+ if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
+ return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
+ return qualifiedGroupInstanceName;
+ }
private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
oldComponentInstance.setName(newComponentInstance.getName());
oldComponentInstance.setModificationTime(System.currentTimeMillis());
oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
+ if ( oldComponentInstance.getGroupInstances() != null )
+ oldComponentInstance.getGroupInstances().forEach( group ->
+ group.setName( getNewGroupName( oldComponentInstance.getNormalizedName() , ValidationUtils.normalizeComponentInstanceName( newComponentInstance.getName() ) , group.getName() ) ) );
return oldComponentInstance;
}
@@ -748,6 +781,17 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
resultOp = Either.right(componentsUtils.getResponseFormat(status, componentInstanceId));
}
}
+ if(resultOp.isLeft() && CollectionUtils.isNotEmpty(containerComponent.getInputs())){
+ List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
+ if(CollectionUtils.isNotEmpty(inputsToDelete)){
+ StorageOperationStatus deleteInputsRes =
+ toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, containerComponent.getComponentType(), inputsToDelete);
+ if(deleteInputsRes != StorageOperationStatus.OK){
+ log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
+ resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId));
+ }
+ }
+ }
return resultOp;
}
@@ -1696,8 +1740,6 @@ public abstract class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
}
}
- protected abstract Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances(org.openecomp.sdc.be.model.Component containerComponent);
-
protected abstract NodeTypeEnum getNodeTypeOfComponentInstanceOrigin();
protected abstract ComponentTypeEnum getComponentTypeOfComponentInstance();
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
index 669b84f229..7214d011e0 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ElementBusinessLogic.java
@@ -20,19 +20,10 @@
package org.openecomp.sdc.be.components.impl;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
+import com.thinkaurelius.titan.core.TitanGraph;
+import fj.data.Either;
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.Optional;
-import java.util.Set;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
@@ -47,24 +38,10 @@ import org.openecomp.sdc.be.datamodel.api.CategoryTypeEnum;
import org.openecomp.sdc.be.datamodel.utils.NodeTypeConvertUtils;
import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum;
+import org.openecomp.sdc.be.datatypes.enums.*;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
-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.ArtifactType;
-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.Product;
-import org.openecomp.sdc.be.model.PropertyScope;
-import org.openecomp.sdc.be.model.Resource;
-import org.openecomp.sdc.be.model.ResourceMetadataDefinition;
-import org.openecomp.sdc.be.model.Service;
-import org.openecomp.sdc.be.model.Tag;
-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.GroupingDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
@@ -87,9 +64,10 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.thinkaurelius.titan.core.TitanGraph;
-
-import fj.data.Either;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("elementsBusinessLogic")
public class ElementBusinessLogic extends BaseBusinessLogic {
@@ -1003,16 +981,16 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
return elementOperation.getDefaultHeatTimeout();
}
- public Either<Map<String, List<? extends Component>>, ResponseFormat> getCatalogComponents(String userId) {
+ public Either<Map<String, List<? extends Component>>, ResponseFormat> getCatalogComponents(String userId, List<OriginTypeEnum> excludeTypes) {
Either<User, ResponseFormat> resp = validateUserExists(userId, "get Catalog Components", false);
if (resp.isRight()) {
return Either.right(resp.right().value());
}
Map<String, List<? extends Component>> resMap = new HashMap<>();
- Either<List<Resource>, StorageOperationStatus> resResources = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.RESOURCE, true);
+ Either<List<Resource>, StorageOperationStatus> resResources = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.RESOURCE,excludeTypes, true);
if (resResources.isLeft()) {
- Either<List<Service>, StorageOperationStatus> resServices = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.SERVICE, true);
+ Either<List<Service>, StorageOperationStatus> resServices = toscaOperationFacade.getCatalogComponents(ComponentTypeEnum.SERVICE,excludeTypes, true);
if (resServices.isLeft()) {
// Either<List<Product>, StorageOperationStatus> resProducts = productOperation.getProductCatalogData(false);
// if (resProducts.isLeft()) {
@@ -1041,7 +1019,7 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
}
if (filters == null || filters.isEmpty()) {
- Either<List<Component>, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum, false);
+ Either<List<Component>, StorageOperationStatus> componentsList = toscaOperationFacade.getCatalogComponents(assetTypeEnum,null, false);
if(componentsList.isRight()) {
return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentsList.right().value())));
}
@@ -1134,15 +1112,15 @@ public class ElementBusinessLogic extends BaseBusinessLogic {
log.debug("getCatalogComponentsByUuidAndAssetType: Corresponding ComponentTypeEnum not allowed for this API");
return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
}
-
+
Either<List<Component>, StorageOperationStatus> componentsListByUuid = toscaOperationFacade.getComponentListByUuid(uuid, additionalPropertiesToMatch);
if(componentsListByUuid.isRight()) {
- log.debug("getCatalogComponentsByUuidAndAssetType: Service fetching failed");
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), ComponentTypeEnum.SERVICE);
+ log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue()+ " fetching failed");
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(componentsListByUuid.right().value(), assetTypeEnum);
return Either.right(componentsUtils.getResponseFormat(actionStatus, uuid));
}
-
- log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + "Service fetching successful");
+
+ log.debug("getCatalogComponentsByUuidAndAssetType: " + assetTypeEnum.getValue() + assetTypeEnum.getValue() + "fetching successful");
return Either.left(componentsListByUuid.left().value());
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java
index f298b0f203..a3d590374f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/GroupBusinessLogic.java
@@ -359,7 +359,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param inTransaction
* @return
*/
- public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction) {
+ public Either<GroupDefinition, ResponseFormat> validateAndUpdateGroupMetadata(String componentId, User user, ComponentTypeEnum componentType, GroupDefinition updatedGroup, boolean inTransaction , boolean shouldLock) {
Either<GroupDefinition, ResponseFormat> result = null;
try {
@@ -396,10 +396,12 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
return result;
}
GroupDefinition currentGroup = currentGroupOpt.get();
- Either<Boolean, ResponseFormat> lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata");
- if (lockResult.isRight()) {
- result = Either.right(lockResult.right().value());
- return result;
+ if ( shouldLock ){
+ Either<Boolean, ResponseFormat> lockResult = lockComponent(componentId, component, "Update GroupDefinition Metadata");
+ if (lockResult.isRight()) {
+ result = Either.right(lockResult.right().value());
+ return result;
+ }
}
// Validate group type is vfModule
if (!currentGroup.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
@@ -417,7 +419,8 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
} else {
titanDao.rollback();
}
- graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
+ if( shouldLock )
+ graphLockOperation.unlockComponent(componentId, componentType.getNodeType());
}
}
@@ -734,7 +737,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
String nameUpdated = groupUpdate.getName();
String nameCurrent = currentGroup.getName();
if (!nameCurrent.equals(nameUpdated)) {
- Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName());
+ Either<Boolean, ResponseFormat> validatNameResponse = validateGroupName(currentGroup.getName(), groupUpdate.getName() ,true);
if (validatNameResponse.isRight()) {
ResponseFormat errorRespons = validatNameResponse.right().value();
return Either.right(errorRespons);
@@ -752,7 +755,7 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
* @param groupUpdateName
* @return
*/
- private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName) {
+ private Either<Boolean, ResponseFormat> validateGroupName(String currentGroupName, String groupUpdateName , boolean isforceNameModification) {
try {
// Check if the group name is in old format.
if (Pattern.compile(Constants.MODULE_OLD_NAME_PATTERN).matcher(groupUpdateName).matches()) {
@@ -771,14 +774,16 @@ public class GroupBusinessLogic extends BaseBusinessLogic {
String[] split2 = groupUpdateName.split("\\.\\.");
String groupUpdateResourceName = split2[0];
String groupUpdateCounter = split2[2];
+ if (!isforceNameModification){ //if not forced ,allow name prefix&suffix validation [no changes]
+ if (!currentResourceName.equals(groupUpdateResourceName)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName));
+ }
- if (!currentResourceName.equals(groupUpdateResourceName)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentResourceName));
+ if (!currentCounter.equals(groupUpdateCounter)) {
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter));
+ }
}
- if (!currentCounter.equals(groupUpdateCounter)) {
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_VF_MODULE_NAME_MODIFICATION, currentCounter));
- }
}
return Either.left(true);
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java
index e535214d70..8a8937740f 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/HealthCheckBusinessLogic.java
@@ -20,7 +20,10 @@
package org.openecomp.sdc.be.components.impl;
+import java.io.IOException;
+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;
@@ -34,16 +37,23 @@ import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
-import javax.servlet.ServletContext;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpStatus;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.util.EntityUtils;
import org.openecomp.sdc.be.components.distribution.engine.DistributionEngineClusterHealth;
import org.openecomp.sdc.be.components.distribution.engine.UebHealthCheckCall;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
+import org.openecomp.sdc.be.config.Configuration;
+import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.IEsHealthCheckDao;
import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
-import org.openecomp.sdc.be.impl.WebAppContextWrapper;
import org.openecomp.sdc.be.switchover.detector.SwitchoverDetector;
-import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.api.HealthCheckInfo;
import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckComponent;
import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
@@ -52,7 +62,9 @@ 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.reflect.TypeToken;
@Component("healthCheckBusinessLogic")
public class HealthCheckBusinessLogic {
@@ -62,6 +74,7 @@ public class HealthCheckBusinessLogic {
private static Logger healthLogger = LoggerFactory.getLogger(BE_HEALTH_LOG_CONTEXT);
private static final String BE_HEALTH_CHECK_STR = "beHealthCheck";
+ private static final String COMPONENT_CHANGED_MESSAGE = "BE Component %s state changed from %s to %s";
@Resource
private TitanGenericDao titanGenericDao;
@@ -72,15 +85,16 @@ public class HealthCheckBusinessLogic {
@Resource
private DistributionEngineClusterHealth distributionEngineClusterHealth;
+ @Resource
+ private CassandraHealthCheck cassandraHealthCheck;
+
@Autowired
private SwitchoverDetector switchoverDetector;
private static Logger log = LoggerFactory.getLogger(HealthCheckBusinessLogic.class.getName());
- private volatile List<HealthCheckInfo> lastBeHealthCheckInfos = null;
+ private volatile List<HealthCheckInfo> prevBeHealthCheckInfos = null;
- // private static volatile HealthCheckBusinessLogic instance;
- //
public HealthCheckBusinessLogic() {
}
@@ -99,9 +113,9 @@ public class HealthCheckBusinessLogic {
@PostConstruct
public void init() {
- lastBeHealthCheckInfos = getBeHealthCheckInfos();
+ prevBeHealthCheckInfos = getBeHealthCheckInfos();
- log.debug("After initializing lastBeHealthCheckInfos: {}", lastBeHealthCheckInfos);
+ log.debug("After initializing prevBeHealthCheckInfos: {}", prevBeHealthCheckInfos);
healthCheckScheduledTask = new HealthCheckScheduledTask();
@@ -111,115 +125,9 @@ public class HealthCheckBusinessLogic {
}
- //
- // public static HealthCheckBusinessLogic getInstance(){
- //// if (instance == null){
- //// instance = init();
- //// }
- // return instance;
- // }
-
- // private synchronized static HealthCheckBusinessLogic init() {
- // if (instance == null){
- // instance = new HealthCheckBusinessLogic();
- // }
- // return instance;
- // }
-
- private List<HealthCheckInfo> getBeHealthCheckInfos(ServletContext servletContext) {
-
- List<HealthCheckInfo> healthCheckInfos = new ArrayList<HealthCheckInfo>();
-
- // BE
- getBeHealthCheck(servletContext, healthCheckInfos);
-
- // ES
- getEsHealthCheck(servletContext, healthCheckInfos);
-
- // Titan
- getTitanHealthCheck(servletContext, healthCheckInfos);
-
- // Distribution Engine
- getDistributionEngineCheck(servletContext, healthCheckInfos);
-
- return healthCheckInfos;
- }
-
- private List<HealthCheckInfo> getBeHealthCheck(ServletContext servletContext, List<HealthCheckInfo> healthCheckInfos) {
- String appVersion = ExternalConfiguration.getAppVersion();
- String description = "OK";
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.BE, HealthCheckStatus.UP, appVersion, description));
- return healthCheckInfos;
- }
-
- public List<HealthCheckInfo> getTitanHealthCheck(ServletContext servletContext, List<HealthCheckInfo> healthCheckInfos) {
- // Titan health check and version
- TitanGenericDao titanStatusDao = (TitanGenericDao) getDao(servletContext, TitanGenericDao.class);
- String description;
- boolean isTitanUp;
-
- try {
- isTitanUp = titanStatusDao.isGraphOpen();
- } catch (Exception e) {
- description = "Titan error: " + e.getMessage();
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.DOWN, null, description));
- return healthCheckInfos;
- }
- if (isTitanUp) {
- description = "OK";
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.UP, null, description));
- } else {
- description = "Titan graph is down";
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.DOWN, null, description));
- }
- return healthCheckInfos;
- }
-
- public List<HealthCheckInfo> getEsHealthCheck(ServletContext servletContext, List<HealthCheckInfo> healthCheckInfos) {
-
- // ES health check and version
- IEsHealthCheckDao esStatusDao = (IEsHealthCheckDao) getDao(servletContext, IEsHealthCheckDao.class);
- HealthCheckStatus healthCheckStatus;
- String description;
-
- try {
- healthCheckStatus = esStatusDao.getClusterHealthStatus();
- } catch (Exception e) {
- healthCheckStatus = HealthCheckStatus.DOWN;
- description = "ES cluster error: " + e.getMessage();
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, healthCheckStatus, null, description));
- return healthCheckInfos;
- }
- if (healthCheckStatus.equals(HealthCheckStatus.DOWN)) {
- description = "ES cluster is down";
- } else {
- description = "OK";
- }
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, healthCheckStatus, null, description));
- return healthCheckInfos;
- }
-
- public Object getDao(ServletContext servletContext, Class<?> clazz) {
- WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
-
- WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(servletContext);
-
- return webApplicationContext.getBean(clazz);
- }
-
- private void getDistributionEngineCheck(ServletContext servletContext, List<HealthCheckInfo> healthCheckInfos) {
-
- DistributionEngineClusterHealth deDao = (DistributionEngineClusterHealth) getDao(servletContext, DistributionEngineClusterHealth.class);
- HealthCheckInfo healthCheckInfo = deDao.getHealthCheckInfo();
+ public boolean isDistributionEngineUp() {
- healthCheckInfos.add(healthCheckInfo);
-
- }
-
- public boolean isDistributionEngineUp(ServletContext servletContext) {
-
- DistributionEngineClusterHealth deDao = (DistributionEngineClusterHealth) getDao(servletContext, DistributionEngineClusterHealth.class);
- HealthCheckInfo healthCheckInfo = deDao.getHealthCheckInfo();
+ HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo();
if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN)) {
return false;
}
@@ -228,7 +136,7 @@ public class HealthCheckBusinessLogic {
public List<HealthCheckInfo> getBeHealthCheckInfosStatus() {
- return lastBeHealthCheckInfos;
+ return prevBeHealthCheckInfos;
}
@@ -241,8 +149,8 @@ public class HealthCheckBusinessLogic {
// BE
getBeHealthCheck(healthCheckInfos);
- // ES
- getEsHealthCheck(healthCheckInfos);
+ /*// ES
+ getEsHealthCheck(healthCheckInfos);*/
// Titan
getTitanHealthCheck(healthCheckInfos);
@@ -250,6 +158,12 @@ public class HealthCheckBusinessLogic {
// Distribution Engine
getDistributionEngineCheck(healthCheckInfos);
+ //Cassandra
+ getCassandraHealthCheck(healthCheckInfos);
+
+ // Amdocs
+ getAmdocsHealthCheck(healthCheckInfos);
+
return healthCheckInfos;
}
@@ -260,7 +174,8 @@ public class HealthCheckBusinessLogic {
return healthCheckInfos;
}
- public List<HealthCheckInfo> getEsHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
+ //Removed from aggregate HC - TDP 293490
+/* private List<HealthCheckInfo> getEsHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
// ES health check and version
HealthCheckStatus healthCheckStatus;
@@ -282,7 +197,7 @@ public class HealthCheckBusinessLogic {
healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, healthCheckStatus, null, description));
return healthCheckInfos;
}
-
+*/
public List<HealthCheckInfo> getTitanHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
// Titan health check and version
String description;
@@ -305,6 +220,28 @@ public class HealthCheckBusinessLogic {
return healthCheckInfos;
}
+ private List<HealthCheckInfo> getCassandraHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
+
+ String description;
+ boolean isCassandraUp;
+
+ try {
+ isCassandraUp = cassandraHealthCheck.getCassandraStatus();
+ } catch (Exception e) {
+ isCassandraUp = false;
+ description = "Cassandra error: " + e.getMessage();
+ }
+ if (isCassandraUp) {
+ description = "OK";
+ healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.CASSANDRA, HealthCheckStatus.UP, null, description));
+ } else {
+ description = "Cassandra is down";
+ healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.CASSANDRA, HealthCheckStatus.DOWN, null, description));
+ }
+ return healthCheckInfos;
+
+ }
+
private void getDistributionEngineCheck(List<HealthCheckInfo> healthCheckInfos) {
HealthCheckInfo healthCheckInfo = distributionEngineClusterHealth.getHealthCheckInfo();
@@ -313,6 +250,76 @@ public class HealthCheckBusinessLogic {
}
+ private List<HealthCheckInfo> getAmdocsHealthCheck(List<HealthCheckInfo> healthCheckInfos) {
+ HealthCheckStatus healthCheckStatus;
+ String description;
+ Map<String, Object> amdocsHC = null;
+ String version = null;
+ List<HealthCheckInfo> componentsInfo = null;
+ CloseableHttpClient httpClient = getHttpClient();
+ String amdocsHealtchCheckUrl = buildHealthCheckUrl();
+ HttpGet httpGet = new HttpGet(amdocsHealtchCheckUrl);
+ CloseableHttpResponse beResponse;
+ int beStatus;
+ try {
+ beResponse = httpClient.execute(httpGet);
+ beStatus = beResponse.getStatusLine().getStatusCode();
+
+ HttpEntity entity = beResponse.getEntity();
+ String beJsonResponse = EntityUtils.toString(entity);
+ Gson gson = new Gson();
+ amdocsHC = gson.fromJson(beJsonResponse, Map.class);
+ version = amdocsHC.get("sdcVersion") != null ? amdocsHC.get("sdcVersion").toString() : null;
+ Object object = amdocsHC.get("componentsInfo");
+ Type listType = new TypeToken<List<HealthCheckInfo>>(){}.getType();
+ componentsInfo = gson.fromJson(object.toString(), listType);
+
+ if (beStatus != HttpStatus.SC_OK) {
+ healthCheckStatus = HealthCheckStatus.DOWN;
+ StringBuilder sb = new StringBuilder();
+ componentsInfo.forEach(x -> {
+ if (x.getHealthCheckStatus()==HealthCheckStatus.DOWN){
+ sb.append("Component "+x.getHealthCheckComponent().name()+" is Down,");
+ }
+ });
+ //Removing the last comma
+ description = sb.length()>0
+ ? sb.substring(0, sb.length()-1)
+ : "Onboarding is Down, specific reason unknown";//No Amdocs inner component returned DOWN, but the status of Amdocs HC is still DOWN.
+ } else {
+ healthCheckStatus = HealthCheckStatus.UP;
+ description = "OK";
+
+
+ }
+
+ } catch (Exception e) {
+ healthCheckStatus = HealthCheckStatus.DOWN;
+ description = "Onboarding unexpected response: " + e.getMessage();
+ } finally {
+ if (httpClient != null) {
+ try {
+ httpClient.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ON_BOARDING, healthCheckStatus, version, description, componentsInfo));
+ return healthCheckInfos;
+ }
+
+ private CloseableHttpClient getHttpClient() {
+ int timeout = 3000;
+ RequestConfig.Builder requestBuilder = RequestConfig.custom();
+ requestBuilder.setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout);
+
+ HttpClientBuilder builder = HttpClientBuilder.create();
+ builder.setDefaultRequestConfig(requestBuilder.build());
+ return builder.build();
+ }
+
@PreDestroy
private void destroy() {
@@ -340,101 +347,127 @@ public class HealthCheckBusinessLogic {
healthLogger.trace("Executing BE Health Check Task");
- List<HealthCheckInfo> beHealthCheckInfos = getBeHealthCheckInfos();
- boolean healthStatus = getAggregateBeStatus(beHealthCheckInfos);
+ List<HealthCheckInfo> currentBeHealthCheckInfos = getBeHealthCheckInfos();
+ boolean healthStatus = getAggregateBeStatus(currentBeHealthCheckInfos);
+
+ boolean prevHealthStatus = getAggregateBeStatus(prevBeHealthCheckInfos);
- boolean lastHealthStatus = getAggregateBeStatus(lastBeHealthCheckInfos);
+ boolean anyStatusChanged = anyStatusChanged(currentBeHealthCheckInfos, prevBeHealthCheckInfos);
- if (lastHealthStatus != healthStatus) {
+ if (prevHealthStatus != healthStatus || anyStatusChanged) {
log.trace("BE Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
- lastBeHealthCheckInfos = beHealthCheckInfos;
+ prevBeHealthCheckInfos = currentBeHealthCheckInfos;
logAlarm(healthStatus);
+ }
- } else {
- // check if we need to update the status's list in case one of
- // the statuses was changed
- if (true == anyStatusChanged(beHealthCheckInfos, lastBeHealthCheckInfos)) {
- lastBeHealthCheckInfos = beHealthCheckInfos;
- }
+ }
- }
+ private boolean getAggregateBeStatus(List<HealthCheckInfo> beHealthCheckInfos) {
+
+ boolean status = true;
+ for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) {
+ if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN) && healthCheckInfo.getHealthCheckComponent() != HealthCheckComponent.DE) {
+ status = false;
+ break;
+ }
+ }
+ return status;
}
}
- private void logAlarm(boolean lastHealthState) {
- if (lastHealthState == true) {
+ private void logAlarm(boolean prevHealthState) {
+ if (prevHealthState) {
BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(BE_HEALTH_CHECK_STR);
} else {
BeEcompErrorManager.getInstance().logBeHealthCheckError(BE_HEALTH_CHECK_STR);
}
}
- private boolean getAggregateBeStatus(List<HealthCheckInfo> beHealthCheckInfos) {
-
- boolean status = true;
-
- for (HealthCheckInfo healthCheckInfo : beHealthCheckInfos) {
- if (healthCheckInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN) && healthCheckInfo.getHealthCheckComponent() != HealthCheckComponent.DE) {
- status = false;
- break;
- }
- }
- return status;
+ private void logAlarm(String componentChangedMsg) {
+ BeEcompErrorManager.getInstance().logBeHealthCheckRecovery(componentChangedMsg);
}
+
public String getSiteMode() {
return switchoverDetector.getSiteMode();
}
- public boolean anyStatusChanged(List<HealthCheckInfo> beHealthCheckInfos, List<HealthCheckInfo> lastBeHealthCheckInfos) {
+ public boolean anyStatusChanged(List<HealthCheckInfo> beHealthCheckInfos, List<HealthCheckInfo> prevBeHealthCheckInfos) {
boolean result = false;
- if (beHealthCheckInfos != null && lastBeHealthCheckInfos != null) {
+ if (beHealthCheckInfos != null && prevBeHealthCheckInfos != null) {
Map<HealthCheckComponent, HealthCheckStatus> currentValues = beHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus()));
- Map<HealthCheckComponent, HealthCheckStatus> lastValues = lastBeHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus()));
+ Map<HealthCheckComponent, HealthCheckStatus> prevValues = prevBeHealthCheckInfos.stream().collect(Collectors.toMap(p -> p.getHealthCheckComponent(), p -> p.getHealthCheckStatus()));
- if (currentValues != null && lastValues != null) {
+ if (currentValues != null && prevValues != null) {
int currentSize = currentValues.size();
- int lastSize = lastValues.size();
+ int prevSize = prevValues.size();
+
+ if (currentSize != prevSize) {
+
+ result = true; //extra/missing component
+
+ Map<HealthCheckComponent, HealthCheckStatus> notPresent = null;
+ if (currentValues.keySet().containsAll(prevValues.keySet())) {
+ notPresent = new HashMap<>(currentValues);
+ notPresent.keySet().removeAll(prevValues.keySet());
+ } else {
+ notPresent = new HashMap<>(prevValues);
+ notPresent.keySet().removeAll(currentValues.keySet());
+ }
+
+ for (HealthCheckComponent component : notPresent.keySet()) {
+ logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, component, prevValues.get(component), currentValues.get(component)));
+ }
+ // HealthCheckComponent changedComponent = notPresent.keySet().iterator().next();
- if (currentSize != lastSize) {
- result = true;
} else {
for (Entry<HealthCheckComponent, HealthCheckStatus> entry : currentValues.entrySet()) {
HealthCheckComponent key = entry.getKey();
HealthCheckStatus value = entry.getValue();
- if (false == lastValues.containsKey(key)) {
- result = true;
+ if (!prevValues.containsKey(key)) {
+ result = true; //component missing
+ logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key)));
break;
}
- HealthCheckStatus lastHealthCheckStatus = lastValues.get(key);
+ HealthCheckStatus prevHealthCheckStatus = prevValues.get(key);
- if (value != lastHealthCheckStatus) {
- result = true;
+ if (value != prevHealthCheckStatus) {
+ result = true; //component status changed
+ logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, key, prevValues.get(key), currentValues.get(key)));
break;
}
}
}
- } else if (currentValues == null && lastValues == null) {
- result = false;
- } else {
- result = true;
}
- } else if (beHealthCheckInfos == null && lastBeHealthCheckInfos == null) {
+ } else if (beHealthCheckInfos == null && prevBeHealthCheckInfos == null) {
result = false;
} else {
+ logAlarm(String.format(COMPONENT_CHANGED_MESSAGE, "", prevBeHealthCheckInfos == null ? "null" : "true", prevBeHealthCheckInfos == null ? "true" : "null"));
result = true;
}
return result;
}
+
+ private String buildHealthCheckUrl() {
+
+ Configuration.OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding();
+
+ String protocol = onboardingConfig.getProtocol();
+ String host = onboardingConfig.getHost();
+ Integer port = onboardingConfig.getPort();
+ String uri = onboardingConfig.getHealthCheckUri();
+
+ return protocol + "://" + host + ":" + port + uri;
+ }
}
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 cded9ee706..c85520dbe4 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
@@ -107,6 +107,7 @@ public final class ImportUtils {
public static final List<String> TOSCA_DEFINITION_VERSIONS = Arrays.asList(new String[] { "tosca_simple_yaml_1_0_0", "tosca_simple_profile_for_nfv_1_0_0", "tosca_simple_yaml_1_0" });
public static final List<String> TOSCA_YML_CSAR_VALID_SUFFIX = Arrays.asList(new String[] { ".yml", ".yaml", ".csar" });
public static final String UI_JSON_PAYLOAD_NAME = "payloadName";
+ public static final String CVFC_DESCRIPTION = "Complex node type that is used as nested type in VF";
}
public enum ResultStatusEnum {
@@ -133,6 +134,7 @@ public final class ImportUtils {
PARAMETERS("parameters"),
// Import Validations
TOSCA_VERSION("tosca_definitions_version"), TOPOLOGY_TEMPLATE("topology_template"), NODE_TYPES("node_types"), OCCURRENCES("occurrences"), NODE_TEMPLATES("node_templates"), GROUPS("groups"), INPUTS("inputs"),
+ SUBSTITUTION_MAPPINGS("substitution_mappings"), NODE_TYPE("node_type"),
// Attributes
ATTRIBUTES("attributes"), LABEL("label"), HIDDEN("hidden"), IMMUTABLE("immutable"), GET_INPUT("get_input");
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 d6497b58ea..f85e25e5fb 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
@@ -456,47 +456,7 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
resList = result.left().value();
- /*int index = 0;
- for (Entry<String, List<InputDefinition>> entry : newInputsMap.entrySet()) {
-
- String compInstId = entry.getKey();
-
- Optional<ComponentInstance> op = ciList.stream().filter(ci -> ci.getUniqueId().equals(compInstId)).findAny();
- if(!op.isPresent()){
- ActionStatus actionStatus = ActionStatus.INVALID_CONTENT;
- log.debug("Failed to find component instance {} under component {}", compInstId, componentId);
- result = Either.right(componentsUtils.getResponseFormat(actionStatus));
- return result;
- }
- ComponentInstance ci = op.get();
- String compInstname = ci.getNormalizedName();
- Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> origComponentEither = getOriginComponent(ci, origComponentMap);
- if(origComponentEither.isRight()){
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(origComponentEither.right().value());
- log.debug("Failed to create inputs value under component {}, error: {}", componentId, actionStatus.name());
- result = Either.right(componentsUtils.getResponseFormat(actionStatus));
- return result;
- }
- org.openecomp.sdc.be.model.Component origComponent = origComponentEither.left().value();
-
- List<InputDefinition> inputs = entry.getValue();
-
- if (inputs != null && !inputs.isEmpty()) {
-
- for (InputDefinition input : inputs) {
-
- StorageOperationStatus status = addInputsToComponent(componentId, inputsToCreate, inputsValueToCreateMap, allDataTypes.left().value(), resList, index, compInstId, compInstname, origComponent, input);
- if(status != StorageOperationStatus.OK ){
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(status);
- log.debug("Failed to create inputs value under component {}, error: {}", componentId, actionStatus.name());
- result = Either.right(componentsUtils.getResponseFormat(actionStatus));
- return result;
- }
-
- }
- }
-
- }*/
+
}
@@ -715,42 +675,38 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
Either<List<InputDefinition>, ResponseFormat> result = Either.left(resList);
List<InputDefinition> resourceProperties = component.getInputs();
- if(inputs != null && !inputs.isEmpty()){
- Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
- if (allDataTypes.isRight()) {
- return Either.right(allDataTypes.right().value());
- }
+ Either<Map<String, DataTypeDefinition>, ResponseFormat> allDataTypes = getAllDataTypes(applicationDataTypeCache);
+ if (allDataTypes.isRight()) {
+ return Either.right(allDataTypes.right().value());
+ }
- Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
+ Map<String, DataTypeDefinition> dataTypes = allDataTypes.left().value();
- for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) {
- String inputName = inputDefinition.getKey();
- inputDefinition.getValue().setName(inputName);
+ for (Map.Entry<String, InputDefinition> inputDefinition : inputs.entrySet()) {
+ String inputName = inputDefinition.getKey();
+ inputDefinition.getValue().setName(inputName);
- Either<InputDefinition, ResponseFormat> preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes);
- if(preparedInputEither.isRight()){
- return Either.right(preparedInputEither.right().value());
- }
-
- }
- if (resourceProperties != null) {
- Map<String, InputDefinition> generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i));
- Either<Map<String, InputDefinition>, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs);
- if(mergeEither.isRight()){
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value()));
- }
- inputs = mergeEither.left().value();
+ Either<InputDefinition, ResponseFormat> preparedInputEither = prepareAndValidateInputBeforeCreate(inputDefinition.getValue(), dataTypes);
+ if(preparedInputEither.isRight()){
+ return Either.right(preparedInputEither.right().value());
}
- Either<List<InputDefinition>, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId());
- if(assotiateInputsEither.isRight()){
- log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value());
- return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value())));
+ }
+ if (resourceProperties != null) {
+ Map<String, InputDefinition> generatedInputs = resourceProperties.stream().collect(Collectors.toMap(i -> i.getName(), i -> i));
+ Either<Map<String, InputDefinition>, String> mergeEither = ToscaDataDefinition.mergeDataMaps(generatedInputs, inputs);
+ if(mergeEither.isRight()){
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_ALREADY_EXIST, mergeEither.right().value()));
}
- result = Either.left(assotiateInputsEither.left().value());
-
+ inputs = mergeEither.left().value();
}
+ Either<List<InputDefinition>, StorageOperationStatus> assotiateInputsEither = toscaOperationFacade.createAndAssociateInputs(inputs, component.getUniqueId());
+ if(assotiateInputsEither.isRight()){
+ log.debug("Failed to create inputs under component {}. Status is {}", component.getUniqueId(), assotiateInputsEither.right().value());
+ return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(assotiateInputsEither.right().value())));
+ }
+ result = Either.left(assotiateInputsEither.left().value());
return result;
}
@@ -901,15 +857,13 @@ public class InputsBusinessLogic extends BaseBusinessLogic {
}
List<ComponentInstanceInput> inputsValue= getComponentInstanceInputsByInputId(component, inputId);
- Map<String, List<ComponentInstanceInput>> insInputsMatToDelete = new HashMap<>();
-
+
if(inputsValue != null && !inputsValue.isEmpty()){
for(ComponentInstanceInput inputValue: inputsValue){
String compInstId = inputValue.getComponentInstanceId();
prepareValueBeforeDelete(compInstId, inputForDelete, inputValue, inputValue.getPath());
status = toscaOperationFacade.updateComponentInstanceInput(component, compInstId, inputValue);
- List<ComponentInstanceInput> inputList = null;
if(status != StorageOperationStatus.OK){
log.debug("Component id: {} update component instance property {} id: {} failed", componentId, inputValue.getUniqueId(), inputId);
deleteEither = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status), component.getName()));
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java
index ab0969358c..7a7148a6a1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ProductComponentInstanceBusinessLogic.java
@@ -30,10 +30,6 @@ import fj.data.Either;
@Component("productComponentInstanceBusinessLogic")
public class ProductComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic {
- @Override
- protected Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances(org.openecomp.sdc.be.model.Component containerComponent) {
- return Either.left(true);
- }
@Override
protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() {
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 cc4a6d9c71..37067e6541 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
@@ -79,6 +79,7 @@ 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.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.ComponentParametersView;
import org.openecomp.sdc.be.model.DataTypeDefinition;
@@ -86,10 +87,12 @@ import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupProperty;
import org.openecomp.sdc.be.model.GroupTypeDefinition;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
+import org.openecomp.sdc.be.model.ImportCsarInfo;
import org.openecomp.sdc.be.model.InputDefinition;
import org.openecomp.sdc.be.model.InterfaceDefinition;
import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.NodeTypeInfo;
import org.openecomp.sdc.be.model.Operation;
import org.openecomp.sdc.be.model.ParsedToscaYamlInfo;
import org.openecomp.sdc.be.model.PropertyDefinition;
@@ -111,13 +114,11 @@ import org.openecomp.sdc.be.model.heat.HeatParameterType;
import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation;
import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
-import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
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.CsarOperation;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
-import org.openecomp.sdc.be.model.operations.impl.InputsOperation;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
@@ -125,6 +126,7 @@ import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.servlets.RepresentationUtils;
import org.openecomp.sdc.be.tosca.CsarUtils;
import org.openecomp.sdc.be.tosca.CsarUtils.NonMetaArtifactInfo;
+import org.openecomp.sdc.be.tosca.ToscaUtils;
import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer;
import org.openecomp.sdc.be.user.IUserBusinessLogic;
import org.openecomp.sdc.be.user.Role;
@@ -203,18 +205,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
@Autowired
private InputsBusinessLogic inputsBusinessLogic;
- @javax.annotation.Resource
- private InputsOperation inputOperation;
-
- // @Autowired
- // private GroupOperation groupOperation;
-
- @Autowired
- private IHeatParametersOperation heatParametersOperation;
-
- // @Autowired
- // private IArtifactOperation artifactOperation;
-
@Autowired
private CompositionBusinessLogic compositionBusinessLogic;
@@ -290,8 +280,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
* the method returns a list of all the resources that are certified, the returned resources are only abstract or only none abstract according to the given param
*
* @param getAbstract
- * @param userId
- * TODO
+ * @param userId TODO
* @return
*/
public Either<List<Resource>, ResponseFormat> getAllCertifiedResources(boolean getAbstract, HighestFilterEnum highestFilter, String userId) {
@@ -301,16 +290,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
Boolean isHighest = null;
switch (highestFilter) {
- case ALL:
- break;
- case HIGHEST_ONLY:
- isHighest = true;
- break;
- case NON_HIGHEST_ONLY:
- isHighest = false;
- break;
- default:
- break;
+ case ALL:
+ break;
+ case HIGHEST_ONLY:
+ isHighest = true;
+ break;
+ case NON_HIGHEST_ONLY:
+ isHighest = false;
+ break;
+ default:
+ break;
}
Either<List<Resource>, StorageOperationStatus> getResponse = toscaOperationFacade.getAllCertifiedResources(getAbstract, isHighest);
@@ -489,7 +478,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Either<Resource, ResponseFormat> updateResourceFromCsar(Resource oldRresource, Resource newRresource, User user, AuditingActionEnum updateResource, boolean inTransaction, Either<Map<String, byte[]>, StorageOperationStatus> csarUIPayload,
- String csarUUID) {
+ String csarUUID) {
// check state
if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.equals(oldRresource.getLifecycleState())) {
@@ -538,19 +527,24 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Either<Resource, ResponseFormat> result = null;
String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
+ String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
Either<Map<String, Resource>, ResponseFormat> parseNodeTypeInfoYamlEither = null;
+ ImportCsarInfo importCsarInfo = new ImportCsarInfo(newRresource.getName(), user, csarUUID, csar.left().value());
+
try {
Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> prepareForUpdate = null;
Resource preparedResource = null;
- Either<ParsedToscaYamlInfo, ResponseFormat> uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, newRresource, toscaYamlCsarStatus.left().value().getValue(), user);
+ Either<ParsedToscaYamlInfo, ResponseFormat> uploadComponentInstanceInfoMap = parseResourceInfoFromYaml(yamlFileName, newRresource, toscaYamlCsarStatus.left().value().getValue(), user, importCsarInfo.getCreatedNodesToscaResourceNames(), null, null);
if (uploadComponentInstanceInfoMap.isRight()) {
ResponseFormat responseFormat = uploadComponentInstanceInfoMap.right().value();
componentsUtils.auditResource(responseFormat, user, newRresource, "", "", updateResource, null);
result = Either.right(responseFormat);
return result;
}
+ Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csar.left().value(), yamlFileContents);
Map<String, UploadComponentInstanceInfo> instances = uploadComponentInstanceInfoMap.left().value().getInstances();
- Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(csar.left().value(), csarUUID, yamlFileName, oldRresource, user, true, instances);
+ Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = findNodeTypesArtifactsToHandle(nodeTypesInfo, csar.left().value(), csarUUID, yamlFileName, oldRresource, user, true,
+ instances);
if (findNodeTypesArtifactsToHandleRes.isRight()) {
log.debug("failed to find node types for update with artifacts during import csar {}. ", csarUUID);
result = Either.right(findNodeTypesArtifactsToHandleRes.right().value());
@@ -567,10 +561,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
preparedResource = prepareForUpdate.left().value().left;
- String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
- parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, user, yamlFileContents, csar.left().value(), false, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts);
+ parseNodeTypeInfoYamlEither = this.handleNodeTypes(yamlFileName, preparedResource, yamlFileContents, false, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo);
if (parseNodeTypeInfoYamlEither.isRight()) {
ResponseFormat responseFormat = parseNodeTypeInfoYamlEither.right().value();
componentsUtils.auditResource(responseFormat, user, preparedResource, "", "", updateResource, null);
@@ -638,7 +631,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
preparedResource = dataModelResponse.left().value();
}
- Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleCsarArtifacts(preparedResource, user, csarUUID, csar.left().value(), createdArtifacts,
+ Either<Resource, ResponseFormat> createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, importCsarInfo, createdArtifacts,
artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), false, true);
if (createdCsarArtifactsEither.isRight()) {
@@ -674,8 +667,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- private Either<Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>>, ResponseFormat> findNodeTypesArtifactsToHandle(Map<String, byte[]> csar, String csarUUID, String yamlFileName, Resource oldResource, User user,
- boolean inTransaction, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
+ 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,
+ boolean inTransaction, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar);
Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = new HashMap<>();
@@ -683,14 +676,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
try {
nodeTypesArtifactsToHandleRes = Either.left(nodeTypesArtifactsToHandle);
- List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlFileName, oldResource.getSystemName(), uploadComponentInstanceInfoMap);
- validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames);
+ Map<String, String> extractedVfcToscaNames = extractVfcToscaNames(nodeTypesInfo, yamlFileName, oldResource.getSystemName(), uploadComponentInstanceInfoMap);
Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> curNodeTypeArtifactsToHandleRes = null;
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);
- for (ImmutablePair<ImmutablePair<String, List<String>>, String> currVfcToscaNameEntry : extractedVfcToscaNames) {
+ for (Entry<String, String> currVfcToscaNameEntry : extractedVfcToscaNames.entrySet()) {
String currVfcToscaName = currVfcToscaNameEntry.getValue();
+ String currNamespace = currVfcToscaNameEntry.getKey();
log.debug("Going to fetch node type with tosca name {}. ", currVfcToscaName);
Either<Resource, StorageOperationStatus> curVfcRes = toscaOperationFacade.getLatestByToscaResourceName(currVfcToscaName);
@@ -706,10 +699,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if (!MapUtils.isEmpty(extractedVfcsArtifacts)) {
List<ArtifactDefinition> currArtifacts = new ArrayList<>();
- for (String currNamespace : currVfcToscaNameEntry.getKey().getValue()) {
- if (extractedVfcsArtifacts.containsKey(currNamespace)) {
- handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace));
- }
+ if (extractedVfcsArtifacts.containsKey(currNamespace)) {
+ handleAndAddExtractedVfcsArtifacts(currArtifacts, extractedVfcsArtifacts.get(currNamespace));
}
curNodeTypeArtifactsToHandleRes = findNodeTypeArtifactsToHandle(curNodeType, currArtifacts);
if (curNodeTypeArtifactsToHandleRes.isRight()) {
@@ -731,7 +722,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
if (MapUtils.isNotEmpty(curNodeTypeArtifactsToHandle)) {
- nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey().getKey(), curNodeTypeArtifactsToHandle);
+ nodeTypesArtifactsToHandle.put(currVfcToscaNameEntry.getKey(), curNodeTypeArtifactsToHandle);
}
}
} catch (Exception e) {
@@ -742,22 +733,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return nodeTypesArtifactsToHandleRes;
}
- private void validateNodeTypeIdentifiers(Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts, List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractedVfcToscaNames) {
- if (extractedVfcsArtifacts != null) {
- List<String> validIdentifiers = new ArrayList<>();
- if (extractedVfcToscaNames != null) {
- extractedVfcToscaNames.stream().forEach(pair -> {
- validIdentifiers.addAll(pair.getKey().getValue());
- validIdentifiers.add(pair.getKey().getKey());
- });
- }
- for (String curIdentifier : extractedVfcsArtifacts.keySet()) {
- if (validIdentifiers != null && !validIdentifiers.contains(curIdentifier))
- log.warn("Warning - VFC identification {} provided in the Artifacts folder of the CSAR is not valid. ", curIdentifier);
- }
- }
- }
-
private Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> findNodeTypeArtifactsToHandle(Resource curNodeType, List<ArtifactDefinition> extractedArtifacts) {
Either<EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>, ResponseFormat> nodeTypeArtifactsToHandleRes = null;
@@ -870,7 +845,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
* @return
*/
public Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
- User user, boolean inTransaction) {
+ User user, boolean inTransaction) {
Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRequestRes;
Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes = null;
Either<Resource, ResponseFormat> changeStateResponse;
@@ -912,32 +887,30 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
@SuppressWarnings("unchecked")
- private List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractVfcToscaNames(Map<String, byte[]> csar, String yamlFileName, String vfResourceName, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
- List<ImmutablePair<ImmutablePair<String, List<String>>, String>> vfcToscaNames = new ArrayList<>();
- Map<String, Object> nodeTypes;
- if (csar != null) {
- nodeTypes = new HashMap<>();
- putNodeTypesFromYaml(csar, yamlFileName, nodeTypes);
- putNodeTypesFromYaml(csar, Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE, nodeTypes);
- putNodeTypesFromYaml(csar, Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE, nodeTypes);
- Map<String,String> nestedServiceTemplatesMap = new HashMap<>();
- for(UploadComponentInstanceInfo ci : uploadComponentInstanceInfoMap.values()){
- if(ci.getProperties() != null && ci.getProperties().containsKey("service_template_filter")){
- String tempName = CsarUtils.DEFINITIONS_PATH + ((Map<String, String>)ci.getProperties().get("service_template_filter").get(0).getValue()).get("substitute_service_template");
- putNodeTypesFromYaml(csar,tempName, nodeTypes);
- nestedServiceTemplatesMap.put(ci.getType(), tempName);
- }
+ private Map<String, String> extractVfcToscaNames(Map<String, NodeTypeInfo> nodeTypesInfo, String yamlFileName, String vfResourceName, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
+ Map<String, String> vfcToscaNames = new HashMap<>();
+
+ Map<String, Object> nodes = extractAllNodes(nodeTypesInfo);
+ if (!nodes.isEmpty()) {
+ Iterator<Entry<String, Object>> nodesNameEntry = nodes.entrySet().iterator();
+ while (nodesNameEntry.hasNext()) {
+ Entry<String, Object> nodeType = nodesNameEntry.next();
+ String toscaResourceName = buildNodeToscaResourceName(vfResourceName, nodeType.getKey());
+ vfcToscaNames.put(nodeType.getKey(), toscaResourceName);
}
+ }
+ return vfcToscaNames;
+ }
- if (!nodeTypes.isEmpty()) {
- Iterator<Entry<String, Object>> nodesNameEntry = nodeTypes.entrySet().iterator();
- while (nodesNameEntry.hasNext()) {
- Entry<String, Object> nodeType = nodesNameEntry.next();
- addVfcToscaNameFindSubstitutes(csar, vfResourceName, vfcToscaNames, nodeType.getKey(), nestedServiceTemplatesMap);
- }
+ private Map<String, Object> extractAllNodes(Map<String, NodeTypeInfo> nodeTypesInfo) {
+ Map<String, Object> nodes = new HashMap<>();
+ for(NodeTypeInfo nodeTypeInfo: nodeTypesInfo.values()){
+ Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(nodeTypeInfo.getMappedToscaTemplate(), ToscaTagNamesEnum.NODE_TYPES);
+ if (eitherNodeTypes.isLeft()) {
+ nodes.putAll(eitherNodeTypes.left().value());
}
}
- return vfcToscaNames;
+ return nodes;
}
@SuppressWarnings("unchecked")
@@ -954,22 +927,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- private void addVfcToscaNameFindSubstitutes(Map<String, byte[]> csar, String vfResourceName, List<ImmutablePair<ImmutablePair<String, List<String>>, String>> vfcToscaNames, String nodeTypeFullName, Map<String, String> nestedServiceTemplatesMap) {
-
- String toscaResourceName = buildNestedVfcToscaResourceName(vfResourceName, nodeTypeFullName);
- String nodeTypeTemplateYamlName =null;
- if(nestedServiceTemplatesMap.containsKey(nodeTypeFullName)){
- nodeTypeTemplateYamlName = nestedServiceTemplatesMap.get(nodeTypeFullName);
- }
- List<String> relatedVfcsToscaNameSpaces = new ArrayList<>();
- relatedVfcsToscaNameSpaces.add(buildNestedVfcToscaNamespace(nodeTypeFullName));
- if (nodeTypeTemplateYamlName!=null && csar.containsKey(nodeTypeTemplateYamlName)) {
- addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, relatedVfcsToscaNameSpaces, nestedServiceTemplatesMap);
- }
- ImmutablePair<String, List<String>> toscaNameSpacesHierarchy = new ImmutablePair<>(nodeTypeFullName, relatedVfcsToscaNameSpaces);
- vfcToscaNames.add(new ImmutablePair<>(toscaNameSpacesHierarchy, toscaResourceName));
- }
-
private void addSubstituteToscaNamespacesRecursively(Map<String, byte[]> csar, String yamlFileName, List<String> toscaNameSpaces, Map<String, String> nestedServiceTemplatesMap) {
Map<String, Object> nodeTypes = new HashMap<>();
@@ -988,12 +945,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
toscaNameSpaces.add(toscaNameSpace);
- String nodeTypeTemplateYamlName =null;
- if(nestedServiceTemplatesMap.containsKey(nodeTypeFullName)){
+ String nodeTypeTemplateYamlName = null;
+ if (nestedServiceTemplatesMap.containsKey(nodeTypeFullName)) {
nodeTypeTemplateYamlName = nestedServiceTemplatesMap.get(nodeTypeFullName);
}
- if (nodeTypeTemplateYamlName!=null && csar.containsKey(nodeTypeTemplateYamlName)) {
+ if (nodeTypeTemplateYamlName != null && csar.containsKey(nodeTypeTemplateYamlName)) {
addSubstituteToscaNamespacesRecursively(csar, nodeTypeTemplateYamlName, toscaNameSpaces, nestedServiceTemplatesMap);
}
}
@@ -1024,7 +981,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
String yamlFileName = toscaYamlCsarStatus.left().value().getKey();
String yamlFileContents = toscaYamlCsarStatus.left().value().getValue();
log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContents);
- Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, user, yamlFileContents, yamlFileName, csar.left().value(), csarUUID);
+
+ Map<String, NodeTypeInfo> nodeTypesInfo = extractNodeTypesInfo(csar.left().value(), yamlFileContents);
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar.left().value(), resource);
+ ImportCsarInfo importCsarInfo = new ImportCsarInfo(resource.getName(), user, csarUUID, csar.left().value());
+ Either<Resource, ResponseFormat> createResourceFromYaml = createResourceFromYaml(resource, yamlFileContents, yamlFileName, nodeTypesInfo, importCsarInfo, nodeTypesArtifactsToCreate, true, false, null);
if (createResourceFromYaml.isRight()) {
log.debug("Couldn't create resource from YAML");
return Either.right(createResourceFromYaml.right().value());
@@ -1035,6 +996,78 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(vfResource);
}
+ @SuppressWarnings("unchecked")
+ private Map<String, NodeTypeInfo> extractNodeTypesInfo(Map<String, byte[]> csar, String yamlFileContent) {
+ Map<String, NodeTypeInfo> nodeTypesInfo = new HashMap<>();
+ List<Entry<String, byte[]>> globalSubstitutes = new ArrayList<>();
+ for (Map.Entry<String, byte[]> entry : csar.entrySet()) {
+ if (Pattern.compile(CsarUtils.SERVICE_TEMPLATE_PATH_PATTERN).matcher(entry.getKey()).matches()) {
+ if (!isGlobalSubstitute(entry.getKey())) {
+ String yamlFileContents = new String(entry.getValue());
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
+ Either<Object, ResultStatusEnum> substitutionMappingsEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS, ToscaElementTypeEnum.MAP);
+ if (substitutionMappingsEither.isLeft()) {
+ Map<String, Object> substitutionMappings = (Map<String, Object>) substitutionMappingsEither.left().value();
+ if (substitutionMappings.containsKey(ToscaTagNamesEnum.NODE_TYPE.getElementName())) {
+ NodeTypeInfo nodeTypeInfo = new NodeTypeInfo();
+ nodeTypeInfo.setType((String) substitutionMappings.get(ToscaTagNamesEnum.NODE_TYPE.getElementName()));
+ nodeTypeInfo.setTemplateFileName(entry.getKey());
+ nodeTypeInfo.setMappedToscaTemplate(mappedToscaTemplate);
+ nodeTypesInfo.put(nodeTypeInfo.getType(), nodeTypeInfo);
+ }
+ }
+ } else {
+ globalSubstitutes.add(entry);
+ }
+ }
+ }
+ if (CollectionUtils.isNotEmpty(globalSubstitutes)) {
+ for (Map.Entry<String, byte[]> entry : globalSubstitutes) {
+ String yamlFileContents = new String(entry.getValue());
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContents);
+ Either<Object, ResultStatusEnum> nodeTypesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES, ToscaElementTypeEnum.MAP);
+ if (nodeTypesEither.isLeft()) {
+ Map<String, Object> nodeTypes = (Map<String, Object>) nodeTypesEither.left().value();
+ for (Entry<String, Object> nodeType : nodeTypes.entrySet()) {
+ Map<String, Object> nodeTypeMap = (Map<String, Object>) nodeType.getValue();
+ if (nodeTypeMap.containsKey(ToscaTagNamesEnum.DERIVED_FROM.getElementName())) {
+ if (nodeTypesInfo.containsKey(nodeType.getKey())) {
+ NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeType.getKey());
+ List<String> derivedFrom = new ArrayList<>();
+ derivedFrom.add((String) nodeTypeMap.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName()));
+ nodeTypeInfo.setDerivedFrom(derivedFrom);
+ }
+ }
+ }
+ }
+ }
+ }
+ markNestedVfc(yamlFileContent, nodeTypesInfo);
+ return nodeTypesInfo;
+ }
+
+ private void markNestedVfc(String yamlFileContent, Map<String, NodeTypeInfo> nodeTypesInfo) {
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(yamlFileContent);
+ Either<Object, ResultStatusEnum> nodeTemplatesEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TEMPLATES, ToscaElementTypeEnum.MAP);
+ if (nodeTemplatesEither.isLeft()) {
+ Map<String, Object> nodeTemplates = (Map<String, Object>) nodeTemplatesEither.left().value();
+ for (Entry<String, Object> nodeTemplateEntry : nodeTemplates.entrySet()) {
+ Map<String, Object> nodeTemplate = (Map<String, Object>) nodeTemplateEntry.getValue();
+ if (nodeTemplate.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
+ String type = (String) nodeTemplate.get(ToscaTagNamesEnum.TYPE.getElementName());
+ if (nodeTypesInfo.containsKey(type)) {
+ NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(type);
+ nodeTypeInfo.setNested(true);
+ }
+ }
+ }
+ }
+ }
+
+ private boolean isGlobalSubstitute(String fileName) {
+ return fileName.equalsIgnoreCase(Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE) || fileName.equalsIgnoreCase(Constants.ABSTRACT_SUBSTITUTE_GLOBAL_TYPES_SERVICE_TEMPLATE);
+ }
+
private Either<ImmutablePair<String, String>, ResponseFormat> validateAndParseCsar(Resource resource, User user, String csarUUID, Either<Map<String, byte[]>, StorageOperationStatus> csar) {
if (csar.isRight()) {
StorageOperationStatus value = csar.right().value();
@@ -1079,8 +1112,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (validateRes.isRight()) {
return Either.right(validateRes.right().value());
}
- // VF "derivedFrom" should be null (or ignored)
- if (!resource.getResourceType().equals(ResourceTypeEnum.VF)) {
+ // VF / PNF "derivedFrom" should be null (or ignored)
+ if (ToscaUtils.isAtomicType(resource)) {
Either<Boolean, ResponseFormat> validateDerivedFromNotEmpty = validateDerivedFromNotEmpty(user, resource, AuditingActionEnum.CREATE_RESOURCE);
if (validateDerivedFromNotEmpty.isRight()) {
return Either.right(validateDerivedFromNotEmpty.right().value());
@@ -1089,26 +1122,31 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return validateResourceBeforeCreate(resource, user, AuditingActionEnum.CREATE_RESOURCE, inTransaction);
}
-
- public Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, User user, String topologyTemplateYaml, String yamlName, Map<String, byte[]> csar, String csarUUID) {
+//resource, yamlFileContents, yamlFileName, nodeTypesInfo,importCsarInfo, nodeTypesArtifactsToCreate, true, false, null
+ private Either<Resource, ResponseFormat> createResourceFromYaml(Resource resource, String topologyTemplateYaml, String yamlName,
+ Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+ boolean shouldLock, boolean inTransaction, String nodeTypeName) {
List<ArtifactDefinition> createdArtifacts = new ArrayList<ArtifactDefinition>();
log.trace("************* createResourceFromYaml before parse yaml ");
- Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(yamlName, resource, topologyTemplateYaml, user);
+ Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceInfoFromYaml(yamlName, resource, topologyTemplateYaml, importCsarInfo.getModifier(), importCsarInfo.getCreatedNodesToscaResourceNames(), nodeTypesInfo, nodeTypeName);
if (parseResourceInfoFromYamlEither.isRight()) {
ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
+ componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
return Either.right(responseFormat);
}
log.trace("************* createResourceFromYaml after parse yaml ");
ParsedToscaYamlInfo parsedToscaYamlInfo = parseResourceInfoFromYamlEither.left().value();
log.debug("The parsed tosca yaml info is {}", parsedToscaYamlInfo);
log.trace("************* createResourceFromYaml before create ");
- Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource, user, parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, csarUUID, csar, createdArtifacts, topologyTemplateYaml);
+ Either<Resource, ResponseFormat> createdResourceResponse = createResourceAndRIsFromYaml(yamlName, resource, parsedToscaYamlInfo,
+ AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml,
+ nodeTypesInfo, importCsarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeTypeName);
log.trace("************* createResourceFromYaml after create ");
if (createdResourceResponse.isRight()) {
ResponseFormat responseFormat = createdResourceResponse.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
+ componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
return Either.right(responseFormat);
}
@@ -1116,48 +1154,109 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, String resourceYml, User user, boolean needLock,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
-
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(resourceYml);
+ @SuppressWarnings("unchecked")
+ public Either<Map<String, Resource>, ResponseFormat> createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, String resourceYml, Map<String, Object> mappedToscaTemplate, boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+ Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo) {
Either<String, ResultStatusEnum> tosca_version = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, ToscaTagNamesEnum.TOSCA_VERSION);
if (tosca_version.isRight()) {
ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_TOSCA_TEMPLATE);
return Either.right(responseFormat);
}
-
Either<Map<String, Object>, ResultStatusEnum> eitherNodeTypes = ImportUtils.findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.NODE_TYPES);
-
Map<String, Resource> nodeTypesResources = new HashMap<>();
Either<Map<String, Resource>, ResponseFormat> result = Either.left(nodeTypesResources);
-
Map<String, Object> mapToConvert = new HashMap<String, Object>();
mapToConvert.put(ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), tosca_version.left().value());
-
+ Resource vfcCreated = null;
if (eitherNodeTypes.isLeft()) {
-
Iterator<Entry<String, Object>> nodesNameValue = eitherNodeTypes.left().value().entrySet().iterator();
-
while (nodesNameValue.hasNext()) {
-
Entry<String, Object> nodeType = nodesNameValue.next();
Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null || nodeTypesArtifactsToHandle.isEmpty() ? null : nodeTypesArtifactsToHandle.get(nodeType.getKey());
- log.trace("************* Going to create node {}", nodeType.getKey());
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, user, mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
- log.trace("************* finished to create node {}", nodeType.getKey());
- if (resourceCreated.isRight()) {
- return Either.right(resourceCreated.right().value());
- }
- Resource vfcCreated = resourceCreated.left().value().getLeft();
- nodeTypesResources.put(nodeType.getKey(), vfcCreated);
+ if (nodeTypesInfo.containsKey(nodeType.getKey())) {
+ log.trace("************* Going to handle nested vfc {}", nodeType.getKey());
+ Either<Resource, ResponseFormat> handleNeatedVfcYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo, nodeType.getKey(), nodeTypesResources);
+ log.trace("************* Finished to handle nested vfc {}", nodeType.getKey());
+ if (handleNeatedVfcYaml.isRight()) {
+ return Either.right(handleNeatedVfcYaml.right().value());
+ }
+ vfcCreated = handleNeatedVfcYaml.left().value();
+ } else if(importCsarInfo.getCreatedNodesToscaResourceNames()!= null && !importCsarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())){
+ log.trace("************* Going to create node {}", nodeType.getKey());
+ Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> resourceCreated = this.createNodeTypeResourceFromYaml(yamlName, nodeType, importCsarInfo.getModifier(), mapToConvert, resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true);
+ log.debug("************* Finished to create node {}", nodeType.getKey());
+
+ if (resourceCreated.isRight()) {
+ return Either.right(resourceCreated.right().value());
+ }
+ vfcCreated = resourceCreated.left().value().getLeft();
+ importCsarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(),vfcCreated.getToscaResourceName());
+ }
+ if (vfcCreated != null) {
+ nodeTypesResources.put(nodeType.getKey(), vfcCreated);
+ }
mapToConvert.remove(ToscaTagNamesEnum.NODE_TYPES.getElementName());
+ }
+ }
+ return result;
+ }
+
+ private Either<Resource, ResponseFormat> handleNestedVfc(Resource resource, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle,
+ List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo,
+ String nodeType, Map<String, Resource> createdResourcesFromdNodeTypeMap) {
+ Either<Resource, ResponseFormat> handleNestedVfcRes = Either.left(resource);
+ String serviceTemplateFileFullName = nodeTypesInfo.get(nodeType).getTemplateFileName();
+ String serviceTemplateFileContent = new String(importCsarInfo.getCsar().get(serviceTemplateFileFullName));
+ Map<String, Object> nestedVfcJsonMap = nodeTypesInfo.get(nodeType).getMappedToscaTemplate();
+
+ Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMapEither = createResourcesFromYamlNodeTypesList(serviceTemplateFileFullName, resource, serviceTemplateFileContent,
+ nestedVfcJsonMap, false, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo);
+ log.debug("************* Finished to create all nodes from yaml {}", serviceTemplateFileFullName);
+ if (createdResourcesFromdNodeTypeMapEither.isRight()) {
+ log.debug("failed to resources from node types status is {}", createdResourcesFromdNodeTypeMapEither.right().value());
+ return Either.right(createdResourcesFromdNodeTypeMapEither.right().value());
+ }
+ createdResourcesFromdNodeTypeMap.putAll(createdResourcesFromdNodeTypeMapEither.left().value());
+
+ if (nestedVfcJsonMap.containsKey(ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) {
+ Resource complexVfc = new Resource();
+ fillComplexVfcMetadata(resource, importCsarInfo, complexVfc, nodeType, nodeTypesInfo, false);
+ if(!importCsarInfo.getCvfcToCreateQueue().contains(nodeType)){
+ importCsarInfo.getCvfcToCreateQueue().add(nodeType);
+ } else {
+ log.debug("CFVC LOOP DETECTED, VSP {}, CVFC {}", importCsarInfo.getVfResourceName(), complexVfc.getName());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.CFVC_LOOP_DETECTED, importCsarInfo.getVfResourceName(), complexVfc.getName()));
}
+ Either<Resource, ResponseFormat> validationRes = validateResourceBeforeCreate(complexVfc, importCsarInfo.getModifier(), AuditingActionEnum.IMPORT_RESOURCE, true);
+ if(validationRes.isRight()){
+ log.debug("Failed to validate complex VFC {}. ", complexVfc.getName());
+ return validationRes;
+ }
+ Map<String, NodeTypeInfo> newNodeTypesInfo = nodeTypesInfo.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getUnmarkedCopy()));
+ markNestedVfc(serviceTemplateFileContent, newNodeTypesInfo);
+ handleNestedVfcRes = createResourceFromYaml(complexVfc, serviceTemplateFileContent, serviceTemplateFileFullName,
+ newNodeTypesInfo, importCsarInfo, nodeTypesArtifactsToHandle, false, true, nodeType);
+ if (handleNestedVfcRes.isRight()) {
+ log.debug("Couldn't create resource from YAML");
+ return Either.right(handleNestedVfcRes.right().value());
+ }
+ importCsarInfo.getCreatedNodesToscaResourceNames().put(nodeType, handleNestedVfcRes.left().value().getToscaResourceName());
+ LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
+ log.debug("Going to certify cvfc {}. ", handleNestedVfcRes.left().value().getName());
+ Either<Resource, ResponseFormat> certRes = propagateStateToCertified(importCsarInfo.getModifier(), handleNestedVfcRes.left().value(), lifecycleChangeInfo, true, false, true);
+ if (certRes.isRight()) {
+ log.debug("Couldn't certify resource {}. ", handleNestedVfcRes.left().value());
+ return certRes;
+ }
+ createdResourcesFromdNodeTypeMap.put(nodeType, certRes.left().value());
+ importCsarInfo.getCvfcToCreateQueue().remove();
}
- return result;
+ return handleNestedVfcRes;
}
private String getNodeTypeActualName(String fullName) {
@@ -1168,40 +1267,44 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeResourceFromYaml(String yamlName, Entry<String, Object> nodeNameValue, User user, Map<String, Object> mapToConvert, Resource resourceVf, boolean needLock,
- Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed) {
Either<UploadResourceInfo, ResponseFormat> resourceMetaData = fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user);
if (resourceMetaData.isRight()) {
return Either.right(resourceMetaData.right().value());
}
+ String csarVfName = resourceVf.getSystemName();
+ String singleVfcYaml = buildNodeTypeYaml(nodeNameValue, mapToConvert, resourceMetaData.left().value().getResourceType(), csarVfName);
+ Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
+ if (eitherCreator.isRight()) {
+ return Either.right(eitherCreator.right().value());
+ }
+ user = eitherCreator.left().value();
+
+ return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed);
+ }
+
+ private String buildNodeTypeYaml(Entry<String, Object> nodeNameValue, Map<String, Object> mapToConvert, String nodeResourceType, String csarVfName) {
// We need to create a Yaml from each node_types in order to create
// resource from each node type using import normative flow.
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
- Map<String, Object> singleVfc = new HashMap<>();
+ Map<String, Object> node = new HashMap<>();
+ node.put(buildNestedToscaResourceName(nodeResourceType, csarVfName, nodeNameValue.getKey()), nodeNameValue.getValue());
+ mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), node);
- String actualName = this.getNodeTypeActualName(nodeNameValue.getKey());
+ return yaml.dumpAsMap(mapToConvert);
+ }
+
+ private String buildNestedToscaResourceName(String nodeResourceType, String csarVfName, String originToscaResourceName) {
+ String actualName = getNodeTypeActualName(originToscaResourceName);
if (!actualName.startsWith(Constants.ABSTRACT)) {
actualName = "." + Constants.ABSTRACT + actualName;
}
-
- // Setting tosca name
- String toscaResourceName = ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + resourceMetaData.left().value().getResourceType().toLowerCase() + '.' + resourceVf.getSystemName() + actualName;
- singleVfc.put(toscaResourceName, nodeNameValue.getValue());
- mapToConvert.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), singleVfc);
-
- String singleVfcYaml = yaml.dumpAsMap(mapToConvert);
-
- Either<User, ResponseFormat> eitherCreator = validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true);
- if (eitherCreator.isRight()) {
- return Either.right(eitherCreator.right().value());
- }
- user = eitherCreator.left().value();
-
- return this.createResourceFromNodeType(singleVfcYaml, resourceMetaData.left().value(), user, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
+ return ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + nodeResourceType.toLowerCase() + '.' + ValidationUtils.convertToSystemName(csarVfName) + actualName;
}
public Either<Boolean, ResponseFormat> validateResourceCreationFromNodeType(Resource resource, User creator) {
@@ -1214,11 +1317,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createResourceFromNodeType(String nodeTypeYaml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction, boolean needLock,
- Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
+ Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed) {
LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction("certification on import", LifecycleChanceActionEnum.CREATE_FROM_CSAR);
Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> this.validateResourceCreationFromNodeType(resource, creator);
- return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts);
+ return this.resourceImportManager.importCertifiedResource(nodeTypeYaml, resourceMetaData, creator, validator, lifecycleChangeInfo, isInTransaction, true, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed);
}
private Either<UploadResourceInfo, ResponseFormat> fillResourceMetadata(String yamlName, Resource resourceVf, String nodeTypeName, User user) {
@@ -1279,20 +1382,76 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(resourceMetaData);
}
- private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource, User user, ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative, String csarUUID,
- Map<String, byte[]> csar, List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml) {
+ private void fillComplexVfcMetadata(Resource resourceVf, ImportCsarInfo importCsarInfo, Resource cvfc, String nodeTypeName, Map<String, NodeTypeInfo> nodeTypesInfo, boolean shouldBeCertified) {
+ NodeTypeInfo nodeTypeInfo = nodeTypesInfo.get(nodeTypeName);
+ cvfc.setName(buildCvfcName(importCsarInfo.getVfResourceName(), nodeTypeName));
+ cvfc.setNormalizedName(ValidationUtils.normaliseComponentName(cvfc.getName()));
+ cvfc.setSystemName(ValidationUtils.convertToSystemName(cvfc.getName()));
+ cvfc.setResourceType(ResourceTypeEnum.CVFC);
+ cvfc.setAbstract(true);
+ cvfc.setDerivedFrom(nodeTypeInfo.getDerivedFrom());
+ cvfc.setDescription(ImportUtils.Constants.CVFC_DESCRIPTION);
+ cvfc.setIcon(ImportUtils.Constants.DEFAULT_ICON);
+ cvfc.setContactId(importCsarInfo.getModifier().getUserId());
+ cvfc.setCreatorUserId(importCsarInfo.getModifier().getUserId());
+ cvfc.setVendorName(resourceVf.getVendorName());
+ cvfc.setVendorRelease(resourceVf.getVendorRelease());
+ cvfc.setResourceVendorModelNumber(resourceVf.getResourceVendorModelNumber());
+ cvfc.setToscaResourceName(buildNestedToscaResourceName(ResourceTypeEnum.VFC.name(), importCsarInfo.getVfResourceName(), nodeTypeName));
+ cvfc.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID());
+
+ List<String> tags = new ArrayList<>();
+ tags.add(cvfc.getName());
+ cvfc.setTags(tags);
+
+ CategoryDefinition category = new CategoryDefinition();
+ category.setName(ImportUtils.Constants.ABSTRACT_CATEGORY_NAME);
+ SubCategoryDefinition subCategory = new SubCategoryDefinition();
+ subCategory.setName(ImportUtils.Constants.ABSTRACT_SUBCATEGORY);
+ category.addSubCategory(subCategory);
+ List<CategoryDefinition> categories = new ArrayList<>();
+ categories.add(category);
+ cvfc.setCategories(categories);
+
+ String version;
+ LifecycleStateEnum state;
+
+ if (shouldBeCertified) {
+ version = ImportUtils.Constants.FIRST_CERTIFIED_VERSION_VERSION;
+ state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE;
+ } else {
+ version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION;
+ state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT;
+ }
+ cvfc.setVersion(version);
+ cvfc.setLifecycleState(state);
+ cvfc.setHighestVersion(ImportUtils.Constants.NORMATIVE_TYPE_HIGHEST_VERSION);
+ }
+
+ private String buildCvfcName(String resourceVfName, String nodeTypeName) {
+ String nameWithouNamespacePrefix = nodeTypeName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+ String[] findTypes = nameWithouNamespacePrefix.split("\\.");
+ String resourceType = findTypes[0];
+ return resourceVfName + "-" + nameWithouNamespacePrefix.substring(resourceType.length() + 1);
+ }
+
+ private Either<Resource, ResponseFormat> createResourceAndRIsFromYaml(String yamlName, Resource resource, ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative,
+ List<ArtifactDefinition> createdArtifacts, String topologyTemplateYaml, Map<String, NodeTypeInfo> nodeTypesInfo,
+ ImportCsarInfo importCsarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate,
+ boolean shouldLock, boolean inTransaction, String nodeTypeName) {
boolean result = true;
- boolean inTransaction = true;
Map<String, Resource> createdVfcs = new HashMap<>();
List<ArtifactDefinition> nodeTypesNewCreatedArtifacts = new ArrayList<>();
- Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
- if (lockResult.isRight()) {
- ResponseFormat responseFormat = lockResult.right().value();
- return Either.right(responseFormat);
- }
- log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
+ if (shouldLock) {
+ Either<Boolean, ResponseFormat> lockResult = lockComponentByName(resource.getSystemName(), resource, "Create Resource");
+ if (lockResult.isRight()) {
+ ResponseFormat responseFormat = lockResult.right().value();
+ return Either.right(responseFormat);
+ }
+ log.debug("name is locked {} status = {}", resource.getSystemName(), lockResult);
+ }
try {
log.trace("************* createResourceFromYaml before full create resource {}", yamlName);
Either<Resource, ResponseFormat> genericResourceEither = fetchAndSetDerivedFromGenericType(resource);
@@ -1300,7 +1459,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
result = false;
return genericResourceEither;
}
- Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, user, isNormative, inTransaction);
+ Either<Resource, ResponseFormat> createResourcesEither = createResourceTransaction(resource, importCsarInfo.getModifier(), isNormative, inTransaction);
log.trace("************* createResourceFromYaml after full create resource {}", yamlName);
if (createResourcesEither.isRight()) {
result = false;
@@ -1313,7 +1472,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
generateInputsFromGenericTypeProperties(resource, genericResourceEither.left().value());
Map<String, InputDefinition> inputs = parsedToscaYamlInfo.getInputs();
- Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, user, inputs, inTransaction);
+ Either<Resource, ResponseFormat> createInputsOnResource = createInputsOnResource(resource, importCsarInfo.getModifier(), inputs, inTransaction);
if (createInputsOnResource.isRight()) {
result = false;
return createInputsOnResource;
@@ -1323,7 +1482,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap = parsedToscaYamlInfo.getInstances();
log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName);
- createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, user, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml, csar, csarUUID, nodeTypesNewCreatedArtifacts, createdVfcs);
+
+ createResourcesEither = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, actionEnum, topologyTemplateYaml,
+ nodeTypesNewCreatedArtifacts, createdVfcs, nodeTypesInfo, importCsarInfo, nodeTypesArtifactsToCreate);
log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName);
if (createResourcesEither.isRight()) {
result = false;
@@ -1346,7 +1507,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} else {
groups = parsedToscaYamlInfo.getGroups();
}
- Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, user, groups);
+ Either<Resource, ResponseFormat> createGroupsOnResource = createGroupsOnResource(resource, importCsarInfo.getModifier(), groups);
if (createGroupsOnResource.isRight()) {
result = false;
return createGroupsOnResource;
@@ -1355,43 +1516,54 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.trace("************* Finished to add groups from yaml {}", yamlName);
log.trace("************* Going to add artifacts from yaml {}", yamlName);
- Either<Resource, ResponseFormat> createdCsarArtifactsEither = this.handleCsarArtifacts(resource, user, csarUUID, csar, createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), false,
- inTransaction);
- log.trace("************* Finished to add artifacts from yaml {}", yamlName);
- if (createdCsarArtifactsEither.isRight()) {
- result = false;
- return createdCsarArtifactsEither;
- }
- resource = createdCsarArtifactsEither.left().value();
+ if(resource.getResourceType() == ResourceTypeEnum.CVFC){
+ if(nodeTypesArtifactsToCreate.containsKey(nodeTypeName) && nodeTypesArtifactsToCreate.get(nodeTypeName) !=null && !nodeTypesArtifactsToCreate.get(nodeTypeName).isEmpty()){
+ Either<List<ArtifactDefinition>, ResponseFormat> handleNodeTypeArtifactsRes =
+ handleNodeTypeArtifacts(resource, nodeTypesArtifactsToCreate.get(nodeTypeName), nodeTypesNewCreatedArtifacts, importCsarInfo.getModifier(), true);
+ if(handleNodeTypeArtifactsRes.isRight()){
+ return Either.right(handleNodeTypeArtifactsRes.right().value());
+ }
+ }
+ } else {
+ Either<Resource, ResponseFormat> createdCsarArtifactsEither = this.handleVfCsarArtifacts(resource, importCsarInfo, createdArtifacts, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), false,
+ inTransaction);
+ log.trace("************* Finished to add artifacts from yaml {}", yamlName);
+ if (createdCsarArtifactsEither.isRight()) {
+ result = false;
+ return createdCsarArtifactsEither;
+ }
+ resource = createdCsarArtifactsEither.left().value();
+ }
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
+ componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", actionEnum, null);
ASDCKpiApi.countCreatedResourcesKPI();
return Either.left(resource);
} finally {
- if (!result) {
- log.warn("operation failed. do rollback");
- titanDao.rollback();
- if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
- createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
- StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
- if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
- ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, resource.getName());
+ if (!inTransaction) {
+ if (!result) {
+ log.warn("operation failed. do rollback");
+ titanDao.rollback();
+ if (!createdArtifacts.isEmpty() || !nodeTypesNewCreatedArtifacts.isEmpty()) {
+ createdArtifacts.addAll(nodeTypesNewCreatedArtifacts);
+ StorageOperationStatus deleteFromEsRes = artifactsBusinessLogic.deleteAllComponentArtifactsIfNotOnGraph(createdArtifacts);
+ if (!deleteFromEsRes.equals(StorageOperationStatus.OK)) {
+ ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(deleteFromEsRes);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(actionStatus, resource.getName());
+ }
+ log.debug("component and all its artifacts were deleted, id = {}", resource.getName());
}
- log.debug("component and all its artifacts were deleted, id = {}", resource.getName());
- }
- } else {
- log.debug("operation success. do commit");
- titanDao.commit();
+ } else {
+ log.debug("operation success. do commit");
+ titanDao.commit();
+ }
+ }
+ if (shouldLock) {
+ graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
}
-
- graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource);
-
}
-
}
private Either<Resource, ResponseFormat> createGroupsOnResource(Resource resource, User user, Map<String, GroupDefinition> groups) {
@@ -1493,11 +1665,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Either<Resource, ResponseFormat> createInputsOnResource(Resource resource, User user, Map<String, InputDefinition> inputs, boolean inTransaction) {
- if (inputs != null && false == inputs.isEmpty()) {
+ List<InputDefinition> resourceProperties = resource.getInputs();
+ if ( (inputs != null && false == inputs.isEmpty()) || (resourceProperties != null && false == resourceProperties.isEmpty()) ) {
- Either<List<InputDefinition>, ResponseFormat> createGroups = inputsBusinessLogic.createInputsInGraph(inputs, resource, user, inTransaction);
- if (createGroups.isRight()) {
- return Either.right(createGroups.right().value());
+ Either<List<InputDefinition>, ResponseFormat> createInputs = inputsBusinessLogic.createInputsInGraph(inputs, resource, user, inTransaction);
+ if (createInputs.isRight()) {
+ return Either.right(createInputs.right().value());
}
} else {
return Either.left(resource);
@@ -1618,12 +1791,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// Filtered Members Of Current Group containing only members which
// are groups
List<String> currGroupFilteredMembers = currGroupMembers.stream().
- // Keep Only Elements of type group and not Resource Instances
- filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
+ // Keep Only Elements of type group and not Resource Instances
+ filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
// Add Filtered Elements to main Set
- peek(innerGroupName -> allGroupMembers.add(innerGroupName)).
+ peek(innerGroupName -> allGroupMembers.add(innerGroupName)).
// Collect results
- collect(Collectors.toList());
+ collect(Collectors.toList());
// Recursively call the method for all the filtered group members
for (String innerGroupName : currGroupFilteredMembers) {
@@ -1649,25 +1822,24 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (!stop) {
final Set<String> allMembers = allGroups.get(groupName).getMembers().keySet();
Set<String> membersOfTypeGroup = allMembers.stream().
- // Filter In Only Group members
- filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
+ // Filter In Only Group members
+ filter(innerGroupName -> allGroups.containsKey(innerGroupName)).
// Collect
- collect(Collectors.toSet());
+ collect(Collectors.toSet());
stop = allGroupMembers.containsAll(membersOfTypeGroup);
}
return stop;
}
- private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource, User user, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum,
- String topologyTemplateYaml, Map<String, byte[]> csar, String csarUUID, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, Resource> createdVfcs) {
+ private Either<Resource, ResponseFormat> createRIAndRelationsFromYaml(String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap, AuditingActionEnum actionEnum,
+ String topologyTemplateYaml, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, Map<String, Resource> createdVfcs,
+ Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo, Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate) {
Either<Resource, ResponseFormat> result;
Either<Resource, ResponseFormat> createResourcesInstancesEither;
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToCreate = findNodeTypeArtifactsToCreate(csar, yamlName, resource, uploadComponentInstanceInfoMap);
-
log.debug("************* Going to create all nodes {}", yamlName);
- Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, user, topologyTemplateYaml, csar, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts);
+ Either<Map<String, Resource>, ResponseFormat> createdResourcesFromdNodeTypeMap = this.handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo);
log.debug("************* Finished to create all nodes {}", yamlName);
if (createdResourcesFromdNodeTypeMap.isRight()) {
log.debug("failed to resources from node types status is {}", createdResourcesFromdNodeTypeMap.right().value());
@@ -1677,7 +1849,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
createdVfcs.putAll(createdResourcesFromdNodeTypeMap.left().value());
log.debug("************* Going to create all resource instances {}", yamlName);
- createResourcesInstancesEither = createResourceInstances(user, yamlName, resource, uploadComponentInstanceInfoMap, true, false, createdResourcesFromdNodeTypeMap.left().value());
+ createResourcesInstancesEither = createResourceInstances(importCsarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap, true, false, createdResourcesFromdNodeTypeMap.left().value());
log.debug("************* Finished to create all resource instances {}", yamlName);
if (createResourcesInstancesEither.isRight()) {
@@ -1687,7 +1859,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
resource = createResourcesInstancesEither.left().value();
log.debug("************* Going to create all relations {}", yamlName);
- createResourcesInstancesEither = createResourceInstancesRelations(user, yamlName, resource, uploadComponentInstanceInfoMap, true, false);
+ createResourcesInstancesEither = createResourceInstancesRelations(importCsarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap, true, false);
log.debug("************* Finished to create all relations {}", yamlName);
@@ -1700,44 +1872,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
log.debug("************* Going to create positions {}", yamlName);
- Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(resource, user.getUserId());
+ Either<List<ComponentInstance>, ResponseFormat> eitherSetPosition = compositionBusinessLogic.setPositionsForComponentInstances(resource, importCsarInfo.getModifier().getUserId());
log.debug("************* Finished to set positions {}", yamlName);
result = eitherSetPosition.isRight() ? Either.right(eitherSetPosition.right().value()) : Either.left(resource);
return result;
}
- private Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> findNodeTypeArtifactsToCreate(Map<String, byte[]> csar, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadComponentInstanceInfoMap) {
+ private Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> findNodeTypeArtifactsToCreate(Map<String, byte[]> csar, Resource resource) {
Map<String, List<ArtifactDefinition>> extractedVfcsArtifacts = CsarUtils.extractVfcsArtifactsFromCsar(csar);
- List<ImmutablePair<ImmutablePair<String, List<String>>, String>> extractedVfcToscaNames = extractVfcToscaNames(csar, yamlName, resource.getSystemName(), uploadComponentInstanceInfoMap);
- validateNodeTypeIdentifiers(extractedVfcsArtifacts, extractedVfcToscaNames);
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle = null;
- if (!extractedVfcsArtifacts.isEmpty() && !extractedVfcToscaNames.isEmpty()) {
- for (ImmutablePair<ImmutablePair<String, List<String>>, String> currToscaNamePair : extractedVfcToscaNames) {
- EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>> curNodeTypeArtifacts = null;
- String currVfcToscaNamespace = currToscaNamePair.getKey().getKey();
- List<String> relatedVfcs = currToscaNamePair.getKey().getValue();
- List<ArtifactDefinition> currArtifactList = null;
-
- for (String currSubstitute : relatedVfcs) {
- if (extractedVfcsArtifacts.containsKey(currSubstitute)) {
- if (MapUtils.isEmpty(curNodeTypeArtifacts)) {
- curNodeTypeArtifacts = new EnumMap<>(ArtifactOperationEnum.class);
- currArtifactList = new ArrayList<>();
- curNodeTypeArtifacts.put(ArtifactOperationEnum.Create, currArtifactList);
- } else {
- currArtifactList = curNodeTypeArtifacts.get(ArtifactOperationEnum.Create);
- }
- handleAndAddExtractedVfcsArtifacts(currArtifactList, extractedVfcsArtifacts.get(currSubstitute));
- }
- }
-
- if (nodeTypesArtifactsToHandle == null) {
- nodeTypesArtifactsToHandle = new HashMap<>();
- }
- nodeTypesArtifactsToHandle.put(currVfcToscaNamespace, curNodeTypeArtifacts);
- }
+ 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;
}
@@ -1754,31 +1903,30 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, User user, String topologyTemplateYaml, Map<String, byte[]> csar, boolean needLock,
- Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
+ @SuppressWarnings("unchecked")
+ private Either<Map<String, Resource>, ResponseFormat> handleNodeTypes(String yamlName, Resource resource, String topologyTemplateYaml, boolean needLock,
+ Map<String, EnumMap<ArtifactOperationEnum, List<ArtifactDefinition>>> nodeTypesArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts,
+ Map<String, NodeTypeInfo> nodeTypesInfo, ImportCsarInfo importCsarInfo) {
Map<String, Resource> createdResourcesFromdNodeTypeMap = new HashMap<>();
Either<Map<String, Resource>, ResponseFormat> result = Either.left(createdResourcesFromdNodeTypeMap);
+ for (Entry<String, NodeTypeInfo> nodeTypeEntry : nodeTypesInfo.entrySet()) {
+ if (nodeTypeEntry.getValue().isNested()) {
- String yamlFileName = Constants.GLOBAL_SUBSTITUTION_TYPES_SERVICE_TEMPLATE;
-
- if (csar != null && csar.containsKey(yamlFileName)) {
- byte[] yamlFileBytes = csar.get(yamlFileName);
- String globalTypesYaml = new String(yamlFileBytes, StandardCharsets.UTF_8);
- Either<Map<String, Resource>, ResponseFormat> createdNodeTypesFromGlobalTypesTemplateEither = this.createResourcesFromYamlNodeTypesList(yamlFileName, resource, globalTypesYaml, user, needLock, nodeTypesArtifactsToHandle,
- nodeTypesNewCreatedArtifacts);
- if (createdNodeTypesFromGlobalTypesTemplateEither.isRight()) {
- ResponseFormat responseFormat = createdNodeTypesFromGlobalTypesTemplateEither.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
- return Either.right(responseFormat);
+ Either<Resource, ResponseFormat> createResourceFromYaml = handleNestedVfc(resource, nodeTypesArtifactsToHandle,
+ nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo, nodeTypeEntry.getKey(), createdResourcesFromdNodeTypeMap);
+ log.trace("************* finished to create node {}", nodeTypeEntry.getKey());
+ if (createResourceFromYaml.isRight()) {
+ return Either.right(createResourceFromYaml.right().value());
+ }
}
- createdResourcesFromdNodeTypeMap.putAll(createdNodeTypesFromGlobalTypesTemplateEither.left().value());
}
-
- Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, topologyTemplateYaml, user, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts);
+ Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(topologyTemplateYaml);
+ Either<Map<String, Resource>, ResponseFormat> createdNodeTypeFromMainTemplateEither = createResourcesFromYamlNodeTypesList(yamlName, resource, topologyTemplateYaml, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle,
+ nodeTypesNewCreatedArtifacts, nodeTypesInfo, importCsarInfo);
if (createdNodeTypeFromMainTemplateEither.isRight()) {
ResponseFormat responseFormat = createdNodeTypeFromMainTemplateEither.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
+ componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
return Either.right(responseFormat);
}
@@ -1791,10 +1939,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return result;
}
- private Either<Resource, ResponseFormat> handleCsarArtifacts(Resource resource, User user, String csarUUID, Map<String, byte[]> csar, List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
- boolean inTransaction) {
+ private Either<Resource, ResponseFormat> handleVfCsarArtifacts(Resource resource, ImportCsarInfo importCsarInfo, List<ArtifactDefinition> createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock,
+ boolean inTransaction) {
- if (csar != null) {
+ if (importCsarInfo.getCsar() != null) {
String vendorLicenseModelId = null;
String vfLicenseModelId = null;
@@ -1811,26 +1959,26 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
// Specific Behavior for license artifacts
- createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+ createOrUpdateSingleNonMetaArtifact(resource, importCsarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
- createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
+ createOrUpdateSingleNonMetaArtifact(resource, importCsarInfo, CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT,
Constants.VF_LICENSE_LABEL, Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, artifactOperation, null, shouldLock, inTransaction);
- Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(csarUUID, csar, resource, user, createdArtifacts, shouldLock, inTransaction, artifactOperation);
+ Either<Resource, ResponseFormat> eitherCreateResult = createOrUpdateNonMetaArtifacts(importCsarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation);
if (eitherCreateResult.isRight()) {
return Either.right(eitherCreateResult.right().value());
}
- Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csar, csarUUID, componentsUtils);
+ Either<ImmutablePair<String, String>, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(importCsarInfo.getCsar(), importCsarInfo.getCsarUUID(), componentsUtils);
if (artifacsMetaCsarStatus.isLeft()) {
String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey();
String artifactsContents = artifacsMetaCsarStatus.left().value().getValue();
Either<Resource, ResponseFormat> createArtifactsFromCsar = Either.left(resource);
if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create)
- createArtifactsFromCsar = createResourceArtifactsFromCsar(csarUUID, csar, resource, user, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
+ createArtifactsFromCsar = createResourceArtifactsFromCsar(importCsarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
else
- createArtifactsFromCsar = updateResourceArtifactsFromCsar(csarUUID, csar, resource, user, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
+ createArtifactsFromCsar = updateResourceArtifactsFromCsar(importCsarInfo, resource, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction);
if (createArtifactsFromCsar.isRight()) {
log.debug("Couldn't create artifacts from artifacts.meta");
return Either.right(createArtifactsFromCsar.right().value());
@@ -1849,7 +1997,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
* Either.right(componentsUtils.getResponseFormat(actionStatus)); } } }
*/
for (String artifactId : artifactsToDelete) {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE,
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, importCsarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE,
resource, null, null, shouldLock, inTransaction);
if (handleDelete.isRight()) {
log.debug("Couldn't delete artifact {}", artifactId);
@@ -1870,18 +2018,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(resource);
}
- private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, User user, String csarUUID, Map<String, byte[]> csar, String artifactPath, String artifactFileName, String artifactType,
- ArtifactGroupTypeEnum artifactGroupType, String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
- boolean inTransaction) {
+ private Either<Boolean, ResponseFormat> createOrUpdateSingleNonMetaArtifact(Resource resource, ImportCsarInfo importCsarInfo, String artifactPath, String artifactFileName, String artifactType,
+ ArtifactGroupTypeEnum artifactGroupType, String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, ArtifactOperationInfo operation, List<ArtifactDefinition> createdArtifacts, boolean shouldLock,
+ boolean inTransaction) {
byte[] artifactFileBytes = null;
- if (csar.containsKey(artifactPath)) {
- artifactFileBytes = csar.get(artifactPath);
+ if (importCsarInfo.getCsar().containsKey(artifactPath)) {
+ artifactFileBytes = importCsarInfo.getCsar().get(artifactPath);
}
Either<Boolean, ResponseFormat> result = Either.left(true);
if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete) {
if (artifactId != null && !artifactId.isEmpty() && artifactFileBytes == null) {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null,
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resource.getUniqueId(), artifactId, importCsarInfo.getModifier(), AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource, null,
null, shouldLock, inTransaction);
if (handleDelete.isRight()) {
result = Either.right(handleDelete.right().value());
@@ -1896,10 +2044,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if (artifactFileBytes != null) {
Map<String, Object> vendorLicenseModelJson = buildJsonForUpdateArtifact(artifactId, artifactFileName, artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, artifactFileBytes, null);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = createOrUpdateCsarArtifactFromJson(resource, user, vendorLicenseModelJson, operation, shouldLock, inTransaction);
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherNonMetaArtifacts = createOrUpdateCsarArtifactFromJson(resource, importCsarInfo.getModifier(), vendorLicenseModelJson, operation, shouldLock, inTransaction);
addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts);
if (eitherNonMetaArtifacts.isRight()) {
- BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + csarUUID, ErrorSeverity.WARNING);
+ BeEcompErrorManager.getInstance().logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + artifactFileName + "With csar uuid: " + importCsarInfo.getCsarUUID(), ErrorSeverity.WARNING);
return Either.right(eitherNonMetaArtifacts.right().value());
}
}
@@ -1930,13 +2078,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(uploadArtifactToService.left().value());
}
- public Either<Resource, ResponseFormat> updateResourceArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts,
- boolean shouldLock, boolean inTransaction) {
+ public Either<Resource, ResponseFormat> updateResourceArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdNewArtifacts,
+ boolean shouldLock, boolean inTransaction) {
- Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, user);
+ Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, importCsarInfo.getModifier());
if (parseResourceInfoFromYamlEither.isRight()) {
ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
+ componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
return Either.right(responseFormat);
}
@@ -1960,7 +2108,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
}
- return createResourceArtifacts(csarUUID, csar, resource, user, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction);
+ return createResourceArtifacts(importCsarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdNewArtifacts, shouldLock, inTransaction);
}
// find master in group
@@ -1996,7 +2144,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<GroupDefinition, MergedArtifactInfo> mergedgroup = mergeGroupInUpdateFlow(groupArtifact, parsedGroup, artifactsToDelete, groupToDelete, jsonMasterArtifacts, createdDeplymentArtifactsAfterDelete);
// Set<String> deletedArtifactsName = new HashSet<String>();
- Either<List<ArtifactDefinition>, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(resource, user, shouldLock, inTransaction, artifactsToDelete, groupToDelete);
+ Either<List<ArtifactDefinition>, ResponseFormat> deletedArtifactsEither = deleteArtifactsInUpdateCsarFlow(resource, importCsarInfo.getModifier(), shouldLock, inTransaction, artifactsToDelete, groupToDelete);
if (deletedArtifactsEither.isRight()) {
log.debug("Failed to delete artifacts. Status is {} ", deletedArtifactsEither.right().value());
@@ -2023,8 +2171,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
////////////// dissociate, associate or create
////////////// artifacts////////////////////////////
- Either<Resource, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(csarUUID, csar, resource, user, createdNewArtifacts, labelCounter, shouldLock, inTransaction, createdDeplymentArtifactsAfterDelete,
- mergedgroup, deletedArtifacts);
+ Either<Resource, ResponseFormat> assDissotiateEither = associateAndDissociateArtifactsToGroup(importCsarInfo, resource, createdNewArtifacts, labelCounter, shouldLock, inTransaction, createdDeplymentArtifactsAfterDelete,
+ mergedgroup, deletedArtifacts);
if (assDissotiateEither.isRight()) {
log.debug("Failed to delete artifacts. Status is {} ", assDissotiateEither.right().value());
@@ -2042,7 +2190,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
groups = resource.getGroups();
- List<GroupDefinition> groupToUpdate = new ArrayList<>();
+
// update vfModule names
Set<GroupDefinition> groupForAssociateWithMembers = mergedgroup.keySet();
if (groups != null && !groups.isEmpty()) {
@@ -2056,30 +2204,22 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
;
for (GroupDefinition updatedGroupDef : groupForAssociateWithMembers) {
- GroupDefinition group = null;
- Optional<GroupDefinition> opGr = groups.stream().filter(p -> p.getUniqueId().equals(updatedGroupDef.getUniqueId())).findAny();
- if (opGr.isPresent()) {
- group = opGr.get();
- groupToUpdate.add(group);
- }
- if (group != null) {
- Map<String, String> members = new HashMap<String, String>();
- Set<String> artifactsGroup = new HashSet<String>();
- artifactsGroup.addAll(group.getArtifacts());
- associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
- if (!members.isEmpty()) {
- group.setMembers(members);
- }
+ if (updatedGroupDef.getMembers() != null && !updatedGroupDef.getMembers().isEmpty()) {
+ updatedGroupDef.getMembers().clear();
+ }
+ Map<String, String> members = new HashMap<String, String>();
+ Set<String> artifactsGroup = new HashSet<String>();
+ artifactsGroup.addAll(updatedGroupDef.getArtifacts());
+ associateMembersToArtifacts(createdNewArtifacts, createdDeplymentArtifactsAfterDelete, heatGroups, artifactsGroup, members);
+ if (!members.isEmpty()) {
+ updatedGroupDef.setMembers(members);
+
}
+
}
- /*
- * if (!groupToUpdate.isEmpty()) { Either<List<GroupDefinition>, ResponseFormat> assotiateGroupEither = groupBusinessLogic.associateMembersToGroup(resource.getUniqueId(), user.getUserId(), ComponentTypeEnum.RESOURCE, groupToUpdate, false,
- * true); if (assotiateGroupEither.isRight()) { log.debug("Failed to associate artifacts to groups. Status is {} ", assotiateGroupEither.right().value()); return Either.right(assotiateGroupEither.right().value());
- *
- * } }
- */
+
}
@@ -2111,7 +2251,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (validateGroupNamesRes.isRight()) {
return Either.right(validateGroupNamesRes.right().value());
}
- Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction);
+ Either<Resource, ResponseFormat> resStatus = createGroupDeploymentArtifactsFromCsar(importCsarInfo, resource, newArtifactsGroup, createdNewArtifacts, createdDeplymentArtifactsAfterDelete, labelCounter, shouldLock, inTransaction);
if (resStatus.isRight())
return resStatus;
}
@@ -2142,7 +2282,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Either<List<ArtifactDefinition>, ResponseFormat> deleteArtifactsInUpdateCsarFlow(Resource resource, User user, boolean shouldLock, boolean inTransaction, Set<ArtifactDefinition> artifactsToDelete,
- Map<String, List<ArtifactDefinition>> groupToDelete) {
+ Map<String, List<ArtifactDefinition>> groupToDelete) {
List<ArtifactDefinition> deletedArtifacts = new ArrayList<ArtifactDefinition>();
String resourceId = resource.getUniqueId();
if (!artifactsToDelete.isEmpty()) {
@@ -2159,9 +2299,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
* deletedArtifacts.add(removeArifactFromGraph.left().value());
*/
- }
-
- else {
+ } else {
Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = artifactsBusinessLogic.handleDelete(resourceId, artifact.getUniqueId(), user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, resource,
null, null, shouldLock, inTransaction);
if (handleDelete.isRight()) {
@@ -2194,8 +2332,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(deletedArtifacts);
}
- private Either<Resource, ResponseFormat> associateAndDissociateArtifactsToGroup(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactDefinition> createdNewArtifacts, int labelCounter, boolean shouldLock,
- boolean inTransaction, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) {
+ private Either<Resource, ResponseFormat> associateAndDissociateArtifactsToGroup(ImportCsarInfo importCsarInfo, Resource resource, List<ArtifactDefinition> createdNewArtifacts, int labelCounter, boolean shouldLock,
+ boolean inTransaction, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete, Map<GroupDefinition, MergedArtifactInfo> mergedgroup, List<ArtifactDefinition> deletedArtifacts) {
Map<GroupDefinition, List<ArtifactTemplateInfo>> artifactsToAssotiate = new HashMap<GroupDefinition, List<ArtifactTemplateInfo>>();
Map<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateMap = new HashMap<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>>();
Either<Resource, ResponseFormat> resEither = Either.left(resource);
@@ -2212,7 +2350,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<ArtifactTemplateInfo> newArtifactsInGroup = entry.getValue().getListToAssociateArtifactToGroup();
if (newArtifactsInGroup != null && !newArtifactsInGroup.isEmpty())
artifactsToAssotiate.put(entry.getKey(), newArtifactsInGroup);
-
List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdate = entry.getValue().getListToUpdateArtifactInGroup();
if (artifactsToUpdate != null && !artifactsToUpdate.isEmpty())
@@ -2224,11 +2361,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (Entry<GroupDefinition, List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>>> artifactsToUpdateEntry : artifactsToUpdateMap.entrySet()) {
List<ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo>> artifactsToUpdateList = artifactsToUpdateEntry.getValue();
GroupDefinition groupToUpdate = artifactsToUpdateEntry.getKey();
-
+
for (ImmutablePair<ArtifactDefinition, ArtifactTemplateInfo> artifact : artifactsToUpdateList) {
String prevUUID = artifact.getKey().getArtifactUUID();
String prevId = artifact.getKey().getUniqueId();
- Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifact.getKey(), artifact.getValue(), updatedArtifacts,
+ Either<ArtifactDefinition, ResponseFormat> updateArtifactEither = updateDeploymentArtifactsFromCsar(importCsarInfo, resource, artifact.getKey(), artifact.getValue(), updatedArtifacts,
artifact.getRight().getRelatedArtifactsInfo(), shouldLock, inTransaction);
if (updateArtifactEither.isRight()) {
log.debug("failed to update artifacts. status is {}", updateArtifactEither.right().value());
@@ -2236,7 +2373,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return resEither;
}
ArtifactDefinition artAfterUpdate = updateArtifactEither.left().value();
- if ( !prevUUID.equals(artAfterUpdate.getArtifactUUID()) || !prevId.equals(artAfterUpdate.getUniqueId()) ){
+ if (!prevUUID.equals(artAfterUpdate.getArtifactUUID()) || !prevId.equals(artAfterUpdate.getUniqueId())) {
groupToUpdate.getArtifacts().remove(prevId);
groupToUpdate.getArtifactsUuid().remove(prevUUID);
groupToUpdate.getArtifacts().add(artAfterUpdate.getUniqueId());
@@ -2251,6 +2388,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (Entry<GroupDefinition, List<ArtifactTemplateInfo>> associateEntry : artifactsToAssotiate.entrySet()) {
List<ArtifactTemplateInfo> associatedArtifact = associateEntry.getValue();
Set<String> arifactsUids = new HashSet<String>();
+ Set<String> arifactsUuids = new HashSet<String>();
for (ArtifactTemplateInfo artifactTemplate : associatedArtifact) { // try
// to
// find
@@ -2261,6 +2399,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (ArtifactDefinition createdArtifact : createdDeplymentArtifactsAfterDelete) {
if (artifactTemplate.getFileName().equalsIgnoreCase(createdArtifact.getArtifactName())) {
arifactsUids.add(createdArtifact.getUniqueId());
+ arifactsUuids.add(createdArtifact.getUniqueId());
isCreate = false;
String heatEnvId = checkAndGetHeatEnvId(createdArtifact);
if (!heatEnvId.isEmpty()) {
@@ -2280,6 +2419,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (ArtifactDefinition createdNewArtifact : createdNewArtifacts) {
if (artifactTemplate.getFileName().equalsIgnoreCase(createdNewArtifact.getArtifactName())) {
arifactsUids.add(createdNewArtifact.getUniqueId());
+ arifactsUuids.add(createdNewArtifact.getUniqueId());
isCreate = false;
String heatEnvId = checkAndGetHeatEnvId(createdNewArtifact);
if (!heatEnvId.isEmpty()) {
@@ -2291,17 +2431,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
if (isCreate) {
- Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
+ Either<ArtifactDefinition, ResponseFormat> createArtifactEither = createDeploymentArtifact(importCsarInfo, resource, ARTIFACTS_PATH, artifactTemplate, createdNewArtifacts, labelCounter, shouldLock, inTransaction);
if (createArtifactEither.isRight()) {
resEither = Either.right(createArtifactEither.right().value());
return resEither;
}
ArtifactDefinition createdArtifact = createArtifactEither.left().value();
arifactsUids.add(createdArtifact.getUniqueId());
+ arifactsUuids.add(createdArtifact.getUniqueId());
ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(createdArtifact.getArtifactType());
if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(createdArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
- resource.getName(), user, resource, null);
+ resource.getName(), importCsarInfo.getModifier(), resource, null);
if (createHeatEnvPlaceHolder.isRight()) {
return Either.right(createHeatEnvPlaceHolder.right().value());
}
@@ -2314,11 +2455,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (arifactsUids.size() > 0) {
List<String> artifactsToAssociate = new ArrayList<String>();
artifactsToAssociate.addAll(arifactsUids);
- GroupDefinition assotiateGroup = new GroupDefinition();
- assotiateGroup.setUniqueId(associateEntry.getKey().getUniqueId());
- assotiateGroup.setArtifacts(artifactsToAssociate);
- associateArtifactGroup.add(assotiateGroup);
-
+ GroupDefinition assotiateGroup = associateEntry.getKey();
+ assotiateGroup.getArtifacts().addAll(arifactsUids);
+ assotiateGroup.getArtifactsUuid().addAll(arifactsUuids);
}
}
@@ -2354,7 +2493,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Map<GroupDefinition, MergedArtifactInfo> mergeGroupInUpdateFlow(Map<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupArtifact, Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup,
- Set<ArtifactDefinition> artifactsToDelete, Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts, List<ArtifactDefinition> createdDeplymentArtifacts) {
+ Set<ArtifactDefinition> artifactsToDelete, Map<String, List<ArtifactDefinition>> groupToDelete, Set<ArtifactTemplateInfo> jsonMasterArtifacts, List<ArtifactDefinition> createdDeplymentArtifacts) {
Map<GroupDefinition, MergedArtifactInfo> mergedgroup = new HashMap<GroupDefinition, MergedArtifactInfo>();
for (Entry<GroupDefinition, Map<ArtifactDefinition, List<ArtifactDefinition>>> groupListEntry : groupArtifact.entrySet()) {
Map<ArtifactDefinition, List<ArtifactDefinition>> createdArtifactMap = groupListEntry.getValue();
@@ -2365,21 +2504,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (ArtifactDefinition artToDelete : listToDelete) {
findArtifactToDelete(parsedGroup, artifactsToDelete, groupListEntry.getKey().getUniqueId(), artToDelete, createdDeplymentArtifacts);
}
- if(artifactsToDelete != null && !artifactsToDelete.isEmpty()){
+ if (artifactsToDelete != null && !artifactsToDelete.isEmpty()) {
GroupDefinition group = groupListEntry.getKey();
- for(ArtifactDefinition artifactDefinition: artifactsToDelete){
+ for (ArtifactDefinition artifactDefinition : artifactsToDelete) {
if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactDefinition.getUniqueId())) {
group.getArtifacts().remove(artifactDefinition.getUniqueId());
-
+
}
if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(artifactDefinition.getArtifactUUID())) {
group.getArtifactsUuid().remove(artifactDefinition.getArtifactUUID());
-
+
}
}
-
+
}
-
+
for (ArtifactTemplateInfo jsonMasterArtifact : jsonMasterArtifacts) {
if (maserArtifact.getArtifactName().equalsIgnoreCase(jsonMasterArtifact.getFileName())) {
MergedArtifactInfo mergedGroup = new MergedArtifactInfo();
@@ -2400,34 +2539,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return mergedgroup;
}
- private Set<String> findArtifactsNotInGroupToDelete(List<GroupDefinition> groups, List<ArtifactDefinition> createdDeplymentArtifactsAfterDelete) {
- Set<String> artifactNotInGroupSet = new HashSet<String>();
- for (ArtifactDefinition artifact : createdDeplymentArtifactsAfterDelete) {
- boolean needToDelete = true;
- if (artifact.getArtifactName().equalsIgnoreCase(Constants.VENDOR_LICENSE_MODEL) || artifact.getArtifactName().equalsIgnoreCase(Constants.VF_LICENSE_MODEL))
- continue;
- if (groups != null) {
- for (GroupDefinition group : groups) {
- List<String> groupArtifactIds = group.getArtifacts();
- if (groupArtifactIds == null || groupArtifactIds.isEmpty()) {
- continue;
- }
- for (String groupArtifactid : groupArtifactIds) {
- if (groupArtifactid.equalsIgnoreCase(artifact.getUniqueId()))
- needToDelete = false;
-
- }
-
- }
- }
- if (needToDelete)
- artifactNotInGroupSet.add(artifact.getUniqueId());
- }
- return artifactNotInGroupSet;
- }
-
private void findArtifactToDelete(Map<ArtifactTemplateInfo, Set<ArtifactTemplateInfo>> parsedGroup, Set<ArtifactDefinition> artifactsToDelete, String deleteGroupId, ArtifactDefinition artifact,
- List<ArtifactDefinition> createdDeplymentArtifacts) {
+ List<ArtifactDefinition> createdDeplymentArtifacts) {
boolean isNeedToDeleteArtifact = true;
String artifactType = artifact.getArtifactType();
ArtifactDefinition generatedFromArt = null;
@@ -2492,20 +2605,20 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts,
- boolean shouldLock, boolean inTransaction) {
+ public Either<Resource, ResponseFormat> createResourceArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, String artifactsMetaFile, String artifactsMetaFileName, List<ArtifactDefinition> createdArtifacts,
+ boolean shouldLock, boolean inTransaction) {
log.debug("parseResourceArtifactsInfoFromFile start");
- Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, user);
+ Either<Map<String, List<ArtifactTemplateInfo>>, ResponseFormat> parseResourceInfoFromYamlEither = parseResourceArtifactsInfoFromFile(resource, artifactsMetaFile, artifactsMetaFileName, importCsarInfo.getModifier());
if (parseResourceInfoFromYamlEither.isRight()) {
ResponseFormat responseFormat = parseResourceInfoFromYamlEither.right().value();
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
+ componentsUtils.auditResource(responseFormat, importCsarInfo.getModifier(), resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
return Either.right(responseFormat);
}
log.debug("parseResourceArtifactsInfoFromFile end");
log.debug("createResourceArtifacts start");
- Either<Resource, ResponseFormat> respStatus = createResourceArtifacts(csarUUID, csar, resource, user, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdArtifacts, shouldLock, inTransaction);
+ Either<Resource, ResponseFormat> respStatus = createResourceArtifacts(importCsarInfo, resource, parseResourceInfoFromYamlEither.left().value(), AuditingActionEnum.CREATE_RESOURCE, createdArtifacts, shouldLock, inTransaction);
if (respStatus.isRight()) {
return respStatus;
}
@@ -2523,8 +2636,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactTemplateInfo> artifactsTemplateList,
- List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shouldLock, boolean inTransaction) {
+ private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList,
+ List<ArtifactDefinition> createdNewArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shouldLock, boolean inTransaction) {
Either<Resource, ResponseFormat> resStatus = Either.left(resource);
List<GroupDefinition> createdGroups = resource.getGroups();
List<GroupDefinition> heatGroups = null;
@@ -2538,7 +2651,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Set<String> artifactsGroup = new HashSet<String>();
Set<String> artifactsUUIDGroup = new HashSet<String>();
- resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
+ resStatus = createDeploymentArtifactsFromCsar(importCsarInfo, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdNewArtifacts, artifactsFromResource, labelCounter, shouldLock, inTransaction);
if (resStatus.isRight())
return resStatus;
@@ -2562,7 +2675,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
prop.setName(Constants.IS_BASE);
prop.setValue(Boolean.toString(groupTemplateInfo.isBase()));
properties.add(prop);
-
+
List<ArtifactDefinition> createdArtifacts = new ArrayList<>();
createdArtifacts.addAll(createdNewArtifacts);
createdArtifacts.addAll(artifactsFromResource);
@@ -2590,15 +2703,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
resource = component.left().value();
- Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, user, ComponentTypeEnum.RESOURCE, needToAdd);
+ Either<List<GroupDefinition>, ResponseFormat> addGroups = groupBusinessLogic.addGroups(resource, importCsarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToAdd);
if (addGroups.isRight())
return Either.right(addGroups.right().value());
return resStatus;
}
- private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
- ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) {
+ private Either<Resource, ResponseFormat> createDeploymentArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
+ ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, List<ArtifactDefinition> artifactsFromResource, int labelCounter, boolean shoudLock, boolean inTransaction) {
Either<Resource, ResponseFormat> resStatus = Either.left(resource);
String artifactFileName = artifactTemplateInfo.getFileName();
String artifactUid = "";
@@ -2646,7 +2759,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// if not exist need to create
if (!alreadyExist) {
- Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
+ Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(importCsarInfo, resource, ARTIFACTS_PATH, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
if (newArtifactEither.isRight()) {
resStatus = Either.right(newArtifactEither.right().value());
return resStatus;
@@ -2657,7 +2770,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
- resource.getName(), user, resource, null);
+ resource.getName(), importCsarInfo.getModifier(), resource, null);
if (createHeatEnvPlaceHolder.isRight()) {
return Either.right(createHeatEnvPlaceHolder.right().value());
}
@@ -2674,7 +2787,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
if (relatedArtifacts != null) {
for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
- resStatus = createDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
+ resStatus = createDeploymentArtifactsFromCsar(importCsarInfo, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, artifactsFromResource, labelCounter, shoudLock, inTransaction);
if (resStatus.isRight())
return resStatus;
}
@@ -2682,8 +2795,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return resStatus;
}
- private Either<Resource, ResponseFormat> createResourceArtifacts(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, Map<String, List<ArtifactTemplateInfo>> artifactsMap, AuditingActionEnum createResource,
- List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) {
+ private Either<Resource, ResponseFormat> createResourceArtifacts(ImportCsarInfo importCsarInfo, Resource resource, Map<String, List<ArtifactTemplateInfo>> artifactsMap, AuditingActionEnum createResource,
+ List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction) {
Either<Resource, ResponseFormat> resStatus = Either.left(resource);
@@ -2691,7 +2804,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
for (List<ArtifactTemplateInfo> groupTemplateList : arifactsCollection) {
if (groupTemplateList != null) {
- resStatus = createGroupDeploymentArtifactsFromCsar(csarUUID, csar, resource, user, groupTemplateList, createdArtifacts, 0, shouldLock, inTransaction);
+ resStatus = createGroupDeploymentArtifactsFromCsar(importCsarInfo, resource, groupTemplateList, createdArtifacts, 0, shouldLock, inTransaction);
if (resStatus.isRight())
return resStatus;
}
@@ -2701,8 +2814,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction,
- ArtifactOperationInfo artifactOperation) {
+ private Either<Resource, ResponseFormat> createOrUpdateNonMetaArtifacts(ImportCsarInfo importCsarInfo, Resource resource, List<ArtifactDefinition> createdArtifacts, boolean shouldLock, boolean inTransaction, ArtifactOperationInfo artifactOperation) {
Either<Resource, ResponseFormat> resStatus = null;
Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
@@ -2710,7 +2822,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
try {
List<NonMetaArtifactInfo> artifactPathAndNameList =
// Stream of file paths contained in csar
- csar.entrySet().stream()
+ importCsarInfo.getCsar().entrySet().stream()
// Filter in only VF artifact path location
.filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
// Validate and add warnings
@@ -2722,13 +2834,19 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// collect to List
.collect(Collectors.toList());
+ Either<Boolean, String> responseFormatEither = validateArtifactNames(artifactPathAndNameList);
+ if (responseFormatEither.isRight()) {
+ return Either.right(getComponentsUtils().getResponseFormatByArtifactId(ActionStatus.ARTIFACT_NAME_INVALID, responseFormatEither.right().value()));
+ }
+
+
EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> vfCsarArtifactsToHandle = null;
if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
vfCsarArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList);
} else {
- Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, user);
+ Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle(resource, artifactPathAndNameList, importCsarInfo.getModifier());
if (findVfCsarArtifactsToHandleRes.isRight()) {
resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value());
@@ -2744,15 +2862,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// Stream of artifacts to be created
currArtifactOperationPair.getValue().stream()
// create each artifact
- .map(e -> createOrUpdateSingleNonMetaArtifact(resource, user, csarUUID, csar, e.getPath(), e.getArtifactName(), e.getArtifactType().getType(), e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
+ .map(e -> createOrUpdateSingleNonMetaArtifact(resource, importCsarInfo, e.getPath(), e.getArtifactName(), e.getArtifactType().getType(), e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(),
CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), artifactsBusinessLogic.new ArtifactOperationInfo(false, false, currArtifactOperationPair.getKey()), createdArtifacts, shouldLock,
inTransaction))
// filter in only error
.filter(e -> e.isRight()).
// Convert the error from either to ResponseFormat
- map(e -> e.right().value()).
+ map(e -> e.right().value()).
// Check if an error occurred
- findAny();
+ findAny();
// Error found on artifact Creation
if (optionalCreateInDBError.isPresent()) {
resStatus = Either.right(optionalCreateInDBError.get());
@@ -2772,6 +2890,17 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return resStatus;
}
+ private Either<Boolean, String> validateArtifactNames(List<NonMetaArtifactInfo> artifactPathAndNameList) {
+ Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME);
+ for (NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) {
+ if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) {
+ return Either.right(nonMetaArtifactInfo.getArtifactName());
+ }
+ }
+ return Either.left(true);
+ }
+
+
private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> findVfCsarArtifactsToHandle(Resource resource, List<NonMetaArtifactInfo> artifactPathAndNameList, User user) {
List<ArtifactDefinition> existingArtifacts = new ArrayList<>();
@@ -2816,8 +2945,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return result;
}
- private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, List<ArtifactTemplateInfo> artifactsTemplateList, List<ArtifactDefinition> createdArtifacts,
- int labelCounter, boolean shouldLock, boolean inTransaction) {
+ private Either<Resource, ResponseFormat> createGroupDeploymentArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, List<ArtifactTemplateInfo> artifactsTemplateList, List<ArtifactDefinition> createdArtifacts,
+ int labelCounter, boolean shouldLock, boolean inTransaction) {
Either<Resource, ResponseFormat> resStatus = Either.left(resource);
List<GroupDefinition> createdGroups = resource.getGroups();
List<GroupDefinition> heatGroups = null;
@@ -2840,7 +2969,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Set<String> artifactsUUIDGroup = new HashSet<String>();
log.debug("createDeploymentArtifactsFromCsar start");
- resStatus = createDeploymentArtifactFromCsar(csarUUID, ARTIFACTS_PATH, csar, resource, user, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
+ resStatus = createDeploymentArtifactFromCsar(importCsarInfo, ARTIFACTS_PATH, resource, artifactsGroup, artifactsUUIDGroup, groupTemplateInfo, createdArtifacts, labelCounter, shouldLock, inTransaction);
log.debug("createDeploymentArtifactsFromCsar end");
if (resStatus.isRight())
return resStatus;
@@ -2895,7 +3024,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
}
- Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), user, ComponentTypeEnum.RESOURCE, needToCreate);
+ Either<List<GroupDefinition>, ResponseFormat> createGroups = groupBusinessLogic.addGroups(component.left().value(), importCsarInfo.getModifier(), ComponentTypeEnum.RESOURCE, needToCreate);
if (createGroups.isRight()) {
return Either.right(createGroups.right().value());
}
@@ -3004,8 +3133,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
- private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(String csarUUID, String artifactPath, Map<String, byte[]> csar, Resource resource, User user, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
- ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
+ private Either<Resource, ResponseFormat> createDeploymentArtifactFromCsar(ImportCsarInfo importCsarInfo, String artifactPath, Resource resource, Set<String> artifactsGroup, Set<String> artifactsUUIDGroup,
+ ArtifactTemplateInfo artifactTemplateInfo, List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
Either<Resource, ResponseFormat> resStatus = Either.left(resource);
String artifactFileName = artifactTemplateInfo.getFileName();
String artifactUid = "";
@@ -3031,7 +3160,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// if not exist need to create
if (!alreadyExist) {
- Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(csarUUID, csar, resource, user, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
+ Either<ArtifactDefinition, ResponseFormat> newArtifactEither = createDeploymentArtifact(importCsarInfo, resource, artifactPath, artifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
if (newArtifactEither.isRight()) {
resStatus = Either.right(newArtifactEither.right().value());
return resStatus;
@@ -3043,7 +3172,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(newArtifact.getArtifactType());
if (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_VOL) {
Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder = artifactsBusinessLogic.createHeatEnvPlaceHolder(newArtifact, ArtifactsBusinessLogic.HEAT_VF_ENV_NAME, resource.getUniqueId(), NodeTypeEnum.Resource,
- resource.getName(), user, resource, null);
+ resource.getName(), importCsarInfo.getModifier(), resource, null);
if (createHeatEnvPlaceHolder.isRight()) {
return Either.right(createHeatEnvPlaceHolder.right().value());
}
@@ -3060,7 +3189,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
List<ArtifactTemplateInfo> relatedArtifacts = artifactTemplateInfo.getRelatedArtifactsInfo();
if (relatedArtifacts != null) {
for (ArtifactTemplateInfo relatedArtifactTemplateInfo : relatedArtifacts) {
- resStatus = createDeploymentArtifactFromCsar(csarUUID, artifactPath, csar, resource, user, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
+ resStatus = createDeploymentArtifactFromCsar(importCsarInfo, artifactPath, resource, artifactsGroup, artifactsUUIDGroup, relatedArtifactTemplateInfo, createdArtifacts, labelCounter, shoudLock, inTransaction);
if (resStatus.isRight())
return resStatus;
}
@@ -3077,10 +3206,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return artifactEnvUid;
}
- private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, String artifactPath, ArtifactTemplateInfo artifactTemplateInfo,
- List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
+ private Either<ArtifactDefinition, ResponseFormat> createDeploymentArtifact(ImportCsarInfo importCsarInfo, Resource resource, String artifactPath, ArtifactTemplateInfo artifactTemplateInfo,
+ List<ArtifactDefinition> createdArtifacts, int labelCounter, boolean shoudLock, boolean inTransaction) {
final String artifactFileName = artifactTemplateInfo.getFileName();
- Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactPath + artifactFileName, artifactFileName, componentsUtils);
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(importCsarInfo.getCsarUUID(), importCsarInfo.getCsar(), artifactPath + artifactFileName, artifactFileName, componentsUtils);
if (artifactContententStatus.isRight()) {
return Either.right(artifactContententStatus.right().value());
}
@@ -3088,7 +3217,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, importCsarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
shoudLock, inTransaction);
if (uploadArtifactToService.isRight())
@@ -3097,7 +3226,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
if (currentInfo.getHeatParameters() != null) {
- Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarUUID, csar, artifactTemplateInfo, currentInfo, false);
+ Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, importCsarInfo, artifactTemplateInfo, currentInfo, false);
if (updateEnvEither.isRight()) {
log.debug("failed to update parameters to artifact {}", artifactFileName);
return Either.right(updateEnvEither.right().value());
@@ -3113,30 +3242,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- private Either<ArtifactDefinition, ResponseFormat> createInformationalArtifact(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, ArtifactTemplateInfo artifactTemplateInfo, int labelCounter, boolean shoudLock,
- boolean inTransaction) {
- final String artifactFileName = artifactTemplateInfo.getFileName();
- String artifactPath = CsarUtils.ARTIFACTS_PATH + CsarUtils.INFORMATIONAL_ARTIFACTS + artifactFileName;
- Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, artifactPath, artifactFileName, componentsUtils);
- if (artifactContententStatus.isRight())
- return Either.right(artifactContententStatus.right().value());
-
- Map<String, Object> json = buildJsonForArtifact(artifactTemplateInfo, artifactContententStatus.left().value().getValue(), labelCounter);
-
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create),
- shoudLock, inTransaction);
-
- if (uploadArtifactToService.isRight())
- return Either.right(uploadArtifactToService.right().value());
-
- ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
-
- return Either.left(currentInfo);
-
- }
-
- private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(String csarUUID, Map<String, byte[]> csar, Resource resource, User user, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo,
- List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean shouldLock, boolean inTransaction) {
+ private Either<ArtifactDefinition, ResponseFormat> updateDeploymentArtifactsFromCsar(ImportCsarInfo importCsarInfo, Resource resource, ArtifactDefinition oldArtifact, ArtifactTemplateInfo artifactTemplateInfo,
+ List<ArtifactDefinition> updatedArtifacts, List<ArtifactTemplateInfo> updatedRequiredArtifacts, boolean shouldLock, boolean inTransaction) {
Either<ArtifactDefinition, ResponseFormat> resStatus = null;
String artifactFileName = artifactTemplateInfo.getFileName();
@@ -3158,7 +3265,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils);
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactContententStatus = CsarValidationUtils.getArtifactsContent(importCsarInfo.getCsarUUID(), importCsarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactFileName, artifactFileName, componentsUtils);
if (artifactContententStatus.isRight()) {
resStatus = Either.right(artifactContententStatus.right().value());
return resStatus;
@@ -3167,7 +3274,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, Object> json = buildJsonForUpdateArtifact(oldArtifact.getUniqueId(), artifactFileName, oldArtifact.getArtifactType(), ArtifactGroupTypeEnum.DEPLOYMENT, oldArtifact.getArtifactLabel(), oldArtifact.getArtifactDisplayName(),
oldArtifact.getDescription(), artifactContententStatus.left().value().getRight(), updatedRequiredArtifacts);
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, user, json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update),
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = createOrUpdateCsarArtifactFromJson(resource, importCsarInfo.getModifier(), json, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update),
shouldLock, inTransaction);
if (uploadArtifactToService.isRight()) {
@@ -3176,7 +3283,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
ArtifactDefinition currentInfo = uploadArtifactToService.left().value().left().value();
- Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, csarUUID, csar, artifactTemplateInfo, currentInfo, true);
+ Either<ArtifactDefinition, ResponseFormat> updateEnvEither = updateHeatParamsFromCsar(resource, importCsarInfo, artifactTemplateInfo, currentInfo, true);
if (updateEnvEither.isRight()) {
log.debug("failed to update parameters to artifact {}", artifactFileName);
resStatus = Either.right(updateEnvEither.right().value());
@@ -3192,11 +3299,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
- private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, String csarUUID, Map<String, byte[]> csar, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
+ private Either<ArtifactDefinition, ResponseFormat> updateHeatParamsFromCsar(Resource resource, ImportCsarInfo importCsarInfo, ArtifactTemplateInfo artifactTemplateInfo, ArtifactDefinition currentInfo, boolean isUpdateEnv) {
Either<ArtifactDefinition, ResponseFormat> resStatus = Either.left(currentInfo);
if (artifactTemplateInfo.getEnv() != null && !artifactTemplateInfo.getEnv().isEmpty()) {
- Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(csarUUID, csar, CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
+ Either<ImmutablePair<String, byte[]>, ResponseFormat> artifactparamsStatus = CsarValidationUtils.getArtifactsContent(importCsarInfo.getCsarUUID(), importCsarInfo.getCsar(), CsarUtils.ARTIFACTS_PATH + artifactTemplateInfo.getEnv(), artifactTemplateInfo.getEnv(),
componentsUtils);
if (artifactparamsStatus.isRight()) {
resStatus = Either.right(artifactparamsStatus.right().value());
@@ -3308,7 +3415,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContentent,
- List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
+ List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
Map<String, Object> json = new HashMap<String, Object>();
if (artifactId != null && !artifactId.isEmpty())
@@ -3446,6 +3553,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Map<String, Resource> originCompMap = new HashMap<>();
List<RequirementCapabilityRelDef> relations = new ArrayList<>();
+ Map<String, List<ComponentInstanceInput>> instInputs = new HashMap<>();
+
for (Entry<String, UploadComponentInstanceInfo> entry : uploadResInstancesMap.entrySet()) {
UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue();
ComponentInstance currentCompInstance = null;
@@ -3477,20 +3586,54 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
} else {
originResource = originCompMap.get(currentCompInstance.getComponentUid());
}
- if (originResource.getCapabilities() != null && !originResource.getCapabilities().isEmpty())
- instCapabilties.put(currentCompInstance, originResource.getCapabilities());
- if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty())
- instRequirements.put(currentCompInstance, originResource.getRequirements());
+ if (originResource.getCapabilities() != null && !originResource.getCapabilities().isEmpty()) {
+ Map<String, List<CapabilityDefinition>> originCapabilities ;
+ if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilitiesNamesToUpdate()) && resource.getResourceType() == ResourceTypeEnum.CVFC) {
+ originCapabilities = new HashMap<>();
+ originResource.getCapabilities().entrySet().stream().forEach(e ->{
+ List<CapabilityDefinition> list = e.getValue().stream().map(l -> new CapabilityDefinition(l)).collect(Collectors.toList());
+ originCapabilities.put(e.getKey(), list);
+ });
+ for (List<CapabilityDefinition> capabilities : originCapabilities.values()) {
+ capabilities.stream().filter(c -> uploadComponentInstanceInfo.getCapabilitiesNamesToUpdate().containsKey(c.getName())).forEach(c -> c.setName(uploadComponentInstanceInfo.getCapabilitiesNamesToUpdate().get(c.getName())));
+ }
+ }else{
+ originCapabilities = originResource.getCapabilities();
+ }
+ instCapabilties.put(currentCompInstance, originCapabilities);
+ }
+ if (originResource.getRequirements() != null && !originResource.getRequirements().isEmpty()) {
+ Map<String, List<RequirementDefinition>> originRequirements;
+ if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getRequirementsNamesToUpdate()) && resource.getResourceType() == ResourceTypeEnum.CVFC) {
+ originRequirements = new HashMap<>();
+ originResource.getRequirements().entrySet().stream().forEach(e ->{
+ List<RequirementDefinition> list = e.getValue().stream().map(l -> new RequirementDefinition(l)).collect(Collectors.toList());
+ originRequirements.put(e.getKey(), list);
+ });
+ for (List<RequirementDefinition> requirements : originRequirements.values()) {
+ requirements.stream().filter(r -> uploadComponentInstanceInfo.getRequirementsNamesToUpdate().containsKey(r.getName())).forEach(r -> r.setName(uploadComponentInstanceInfo.getRequirementsNamesToUpdate().get(r.getName())));
+ }
+ }else{
+ originRequirements = originResource.getRequirements();
+ }
+ instRequirements.put(currentCompInstance, originRequirements);
+ }
if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty())
instArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts());
if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty())
instAttributes.put(resourceInstanceId, originResource.getAttributes());
-
- ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
- if (addPropertiesValueToRiRes.getStatus() != 200) {
- return Either.right(addPropertiesValueToRiRes);
+ if (originResource.getResourceType() != ResourceTypeEnum.CVFC) {
+ ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instProperties, allDataTypes.left().value());
+ if (addPropertiesValueToRiRes.getStatus() != 200) {
+ return Either.right(addPropertiesValueToRiRes);
+ }
+ } else {
+ // TO DO
+ ResponseFormat addInputValueToRiRes = addInputsValuesToRi(uploadComponentInstanceInfo, resource, originResource, currentCompInstance, yamlName, instInputs, allDataTypes.left().value());
+ if (addInputValueToRiRes.getStatus() != 200) {
+ return Either.right(addInputValueToRiRes);
+ }
}
-
}
Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addPropToInst = toscaOperationFacade.associateComponentInstancePropertiesToComponent(instProperties, resource.getUniqueId());
@@ -3499,7 +3642,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addPropToInst.right().value()), yamlName);
return Either.right(responseFormat);
}
-
+ if (instInputs != null && !instInputs.isEmpty()) {
+ Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addInputToInst = toscaOperationFacade.associateComponentInstanceInputsToComponent(instInputs, resource.getUniqueId());
+ if (addInputToInst.isRight()) {
+ log.debug("failed to associate inputs value of resource {} status is {}", resource.getUniqueId(), addInputToInst.right().value());
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addInputToInst.right().value()), yamlName);
+ return Either.right(responseFormat);
+ }
+ }
StorageOperationStatus addArtToInst = toscaOperationFacade.associateArtifactToInstances(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);
@@ -3609,89 +3759,187 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
String resourceInstanceId = currentCompInstance.getUniqueId();
- log.debug("************* addPropertyValuesToRi start");
- long startAddProperty = System.currentTimeMillis();
- log.debug("************* addPropertyValuesToRi end");
- totalCreatePropVal += (System.currentTimeMillis() - startAddProperty);
Map<String, List<UploadReqInfo>> regMap = uploadComponentInstanceInfo.getRequirements();
- if (regMap == null) {
+
+ if (regMap != null) {
+ Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
+
+ long startAddRelation = System.currentTimeMillis();
+
+ while (nodesRegValue.hasNext()) {
+ Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
+
+ List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
+ for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
+ log.debug("Going to create relation {}", uploadRegInfo.getName());
+ String regName = uploadRegInfo.getName();
+ RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
+ regCapRelDef.setFromNode(resourceInstanceId);
+ log.debug("try to find available requirement {} ", regName);
+ Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance, uploadRegInfo.getCapabilityName());
+ if (eitherReqStatus.isRight()) {
+ log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
+ return eitherReqStatus.right().value();
+ }
+
+ RequirementDefinition validReq = eitherReqStatus.left().value();
+ List<RequirementAndRelationshipPair> reqAndRelationshipPairList = regCapRelDef.getRelationships();
+ if (reqAndRelationshipPairList == null)
+ reqAndRelationshipPairList = new ArrayList<RequirementAndRelationshipPair>();
+ RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair();
+ reqAndRelationshipPair.setRequirement(regName);
+ reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
+ reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
+ RelationshipImpl relationship = new RelationshipImpl();
+ relationship.setType(validReq.getCapability());
+ reqAndRelationshipPair.setRelationships(relationship);
+
+ ComponentInstance currentCapCompInstance = null;
+ for (ComponentInstance compInstance : componentInstancesList) {
+ if (compInstance.getName().equals(uploadRegInfo.getNode())) {
+ currentCapCompInstance = compInstance;
+ break;
+ }
+ }
+
+ if (currentCapCompInstance == null) {
+ log.debug("The component instance with name {} not found on resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ return responseFormat;
+ }
+ regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
+ log.debug("try to find aviable Capability req name is {} ", validReq.getName());
+ CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
+ if (aviableCapForRel == null) {
+ log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId());
+ BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(),
+ ErrorSeverity.ERROR);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ return responseFormat;
+ }
+ reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
+ reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
+ reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
+ reqAndRelationshipPairList.add(reqAndRelationshipPair);
+ regCapRelDef.setRelationships(reqAndRelationshipPairList);
+ relations.add(regCapRelDef);
+ }
+ }
+ totalCreateRel += (System.currentTimeMillis() - startAddRelation);
+ } else if (resource.getResourceType() != ResourceTypeEnum.CVFC) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK, yamlName);
return responseFormat;
}
- Iterator<Entry<String, List<UploadReqInfo>>> nodesRegValue = regMap.entrySet().iterator();
-
- long startAddRelation = System.currentTimeMillis();
-
- while (nodesRegValue.hasNext()) {
- Entry<String, List<UploadReqInfo>> nodesRegInfoEntry = nodesRegValue.next();
-
- List<UploadReqInfo> uploadRegInfoList = nodesRegInfoEntry.getValue();
- for (UploadReqInfo uploadRegInfo : uploadRegInfoList) {
- log.debug("Going to create relation {}", uploadRegInfo.getName());
- String regName = uploadRegInfo.getName();
- String nodeCapName = uploadRegInfo.getNode();
- RequirementCapabilityRelDef regCapRelDef = new RequirementCapabilityRelDef();
- regCapRelDef.setFromNode(resourceInstanceId);
- log.debug("try to find available requirement {} ", regName);
- Either<RequirementDefinition, ResponseFormat> eitherReqStatus = findAviableRequiremen(regName, yamlName, uploadComponentInstanceInfo, currentCompInstance, uploadRegInfo.getCapabilityName());
- if (eitherReqStatus.isRight()) {
- log.debug("failed to find available requirement {} status is {}", regName, eitherReqStatus.right().value());
- return eitherReqStatus.right().value();
- }
-
- RequirementDefinition validReq = eitherReqStatus.left().value();
- List<RequirementAndRelationshipPair> reqAndRelationshipPairList = regCapRelDef.getRelationships();
- if (reqAndRelationshipPairList == null)
- reqAndRelationshipPairList = new ArrayList<RequirementAndRelationshipPair>();
- RequirementAndRelationshipPair reqAndRelationshipPair = new RequirementAndRelationshipPair();
- reqAndRelationshipPair.setRequirement(regName);
- reqAndRelationshipPair.setRequirementOwnerId(validReq.getOwnerId());
- reqAndRelationshipPair.setRequirementUid(validReq.getUniqueId());
- RelationshipImpl relationship = new RelationshipImpl();
- relationship.setType(validReq.getCapability());
- reqAndRelationshipPair.setRelationships(relationship);
-
- ComponentInstance currentCapCompInstance = null;
- for (ComponentInstance compInstance : componentInstancesList) {
- if (compInstance.getName().equals(uploadRegInfo.getNode())) {
- currentCapCompInstance = compInstance;
- break;
- }
+ return componentsUtils.getResponseFormat(ActionStatus.OK);
+ }
+
+ private ResponseFormat addInputsValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
+ Map<String, List<ComponentInstanceInput>> instInputs, Map<String, DataTypeDefinition> allDataTypes) {
+ Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
+ if (propMap != null && propMap.size() > 0) {
+ Map<String, InputDefinition> currPropertiesMap = new HashMap<String, InputDefinition>();
+
+ int index = 0;
+ List<InputDefinition> listFromMap = originResource.getInputs();
+ if (listFromMap == null || listFromMap.isEmpty()) {
+ log.debug("failed to find properties ");
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND);
+ return responseFormat;
+ }
+ for (InputDefinition prop : listFromMap) {
+ String propName = prop.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ currPropertiesMap.put(propName, prop);
}
+ }
+ List<ComponentInstanceInput> instPropList = new ArrayList<>();
+ for (List<UploadPropInfo> propertyList : propMap.values()) {
- if (currentCapCompInstance == null) {
- log.debug("component instance with name {} in resource {} ", uploadRegInfo.getNode(), resource.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError("component instance with name " + uploadRegInfo.getNode() + " in resource {} ", resource.getUniqueId(), ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
+ UploadPropInfo propertyInfo = propertyList.get(0);
+ String propName = propertyInfo.getName();
+ if (!currPropertiesMap.containsKey(propName)) {
+ log.debug("failed to find property {} ", propName);
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, propName);
return responseFormat;
}
- regCapRelDef.setToNode(currentCapCompInstance.getUniqueId());
- log.debug("try to find aviable Capability req name is {} ", validReq.getName());
- CapabilityDefinition aviableCapForRel = findAvailableCapabilityByTypeOrName(validReq, currentCapCompInstance, uploadRegInfo);
- if (aviableCapForRel == null) {
- log.debug("aviable capability was not found. req name is {} component instance is {}", validReq.getName(), currentCapCompInstance.getUniqueId());
- BeEcompErrorManager.getInstance().logInternalDataError("aviable capability was not found. req name is " + validReq.getName() + " component instance is " + currentCapCompInstance.getUniqueId(), resource.getUniqueId(),
- ErrorSeverity.ERROR);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName);
- return responseFormat;
+ InputDefinition curPropertyDef = currPropertiesMap.get(propName);
+ ComponentInstanceInput property = null;
+
+ String value = null;
+ List<GetInputValueDataDefinition> getInputs = null;
+ boolean isValidate = true;
+ if (propertyInfo.getValue() != null) {
+ getInputs = propertyInfo.getGet_input();
+ isValidate = getInputs == null || getInputs.isEmpty();
+ if (isValidate) {
+ value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), curPropertyDef.getType());
+ } else
+ value = ImportUtils.getPropertyJsonStringValue(propertyInfo.getValue(), ToscaTagNamesEnum.GET_INPUT.getElementName());
}
- reqAndRelationshipPair.setCapability(aviableCapForRel.getName());
- reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId());
- reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId());
- reqAndRelationshipPairList.add(reqAndRelationshipPair);
- regCapRelDef.setRelationships(reqAndRelationshipPairList);
- relations.add(regCapRelDef);
+ String innerType = null;
+ property = new ComponentInstanceInput(curPropertyDef, value, null);
- }
+ Either<String, StorageOperationStatus> validatevalueEiter = validatePropValueBeforeCreate(property, value, isValidate, innerType, allDataTypes);
+ if (validatevalueEiter.isRight()) {
+ return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(validatevalueEiter.right().value()));
+ }
- }
- totalCreateRel += (System.currentTimeMillis() - startAddRelation);
+ // String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(currentCompInstance.getComponentUid(), index++);
+ // property.setUniqueId(uniqueId);
+ property.setValue(validatevalueEiter.left().value());
+
+ if (getInputs != null && !getInputs.isEmpty()) {
+ List<GetInputValueDataDefinition> getInputValues = new ArrayList<>();
+ for (GetInputValueDataDefinition getInput : getInputs) {
+ List<InputDefinition> inputs = resource.getInputs();
+ if (inputs == null || inputs.isEmpty()) {
+ log.debug("Failed to add property {} to resource instance {}. Inputs list is empty ", property, currentCompInstance.getUniqueId());
+ return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ }
+ Optional<InputDefinition> optional = inputs.stream().filter(p -> p.getName().equals(getInput.getInputName())).findAny();
+ if (!optional.isPresent()) {
+ log.debug("Failed to find input {} ", getInput.getInputName());
+ // @@TODO error message
+ return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ }
+ InputDefinition input = optional.get();
+ getInput.setInputId(input.getUniqueId());
+ getInputValues.add(getInput);
+
+ GetInputValueDataDefinition getInputIndex = getInput.getGetInputIndex();
+ if (getInputIndex != null) {
+ optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())).findAny();
+ if (!optional.isPresent()) {
+ log.debug("Failed to find input {} ", getInputIndex.getInputName());
+ // @@TODO error message
+ return componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
+ }
+ InputDefinition inputIndex = optional.get();
+ getInputIndex.setInputId(inputIndex.getUniqueId());
+ getInputValues.add(getInputIndex);
+ }
+ }
+ property.setGetInputValues(getInputValues);
+ }
+ instPropList.add(property);
+ // delete overriden property
+ currPropertiesMap.remove(property.getName());
+ }
+ // add rest of properties
+ if (!currPropertiesMap.isEmpty()) {
+ for (InputDefinition value : currPropertiesMap.values()) {
+ instPropList.add(new ComponentInstanceInput(value));
+ }
+ }
+ instInputs.put(currentCompInstance.getUniqueId(), instPropList);
+ }
return componentsUtils.getResponseFormat(ActionStatus.OK);
}
private ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, Resource resource, Resource originResource, ComponentInstance currentCompInstance, String yamlName,
- Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
+ Map<String, List<ComponentInstanceProperty>> instProperties, Map<String, DataTypeDefinition> allDataTypes) {
Map<String, List<UploadPropInfo>> propMap = uploadComponentInstanceInfo.getProperties();
if (propMap != null && propMap.size() > 0) {
@@ -3845,14 +4093,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return cap;
}
- private RequirementAndRelationshipPair getReqRelPair(CapabilityDefinition cap) {
- RequirementAndRelationshipPair relationPair = new RequirementAndRelationshipPair();
- relationPair.setCapabilityUid(cap.getUniqueId());
- relationPair.setCapability(cap.getName());
- relationPair.setCapabilityOwnerId(cap.getOwnerId());
- return relationPair;
- }
-
private CapabilityDefinition findAviableCapability(RequirementDefinition validReq, ComponentInstance currentCapCompInstance) {
CapabilityDefinition aviableCapForRel = null;
Map<String, List<CapabilityDefinition>> capMap = currentCapCompInstance.getCapabilities();
@@ -3955,9 +4195,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
@SuppressWarnings("unchecked")
- public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, User user) {
+ public Either<ParsedToscaYamlInfo, ResponseFormat> parseResourceInfoFromYaml(String yamlFileName, Resource resource, String resourceYml, User user, Map<String, String> createdNodesToscaResourceNames, Map<String, NodeTypeInfo> nodeTypesInfo, String nodeTypeName) {
- Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(resourceYml);
+ Map<String, Object> mappedToscaTemplate;
+ if(nodeTypesInfo != null && nodeTypeName != null && nodeTypesInfo.containsKey(nodeTypeName)){
+ mappedToscaTemplate = nodeTypesInfo.get(nodeTypeName).getMappedToscaTemplate();
+ }
+ else {
+ mappedToscaTemplate = (Map<String, Object>) new Yaml().load(resourceYml);
+ }
Either<Object, ResultStatusEnum> toscaElementEither = ImportUtils.findToscaElement(mappedToscaTemplate, ToscaTagNamesEnum.TOPOLOGY_TEMPLATE, ToscaElementTypeEnum.ALL);
if (toscaElementEither.isRight()) {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE);
@@ -3970,7 +4216,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
- Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(yamlFileName, mappedToscaTemplate, resource);
+ Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> uploadResInstancesEither = createResourcesInstanceInfoFromYaml(yamlFileName, mappedToscaTemplate, resource, createdNodesToscaResourceNames);
if (uploadResInstancesEither.isRight()) {
ResponseFormat responseFormat = uploadResInstancesEither.right().value();
return Either.right(responseFormat);
@@ -3991,7 +4237,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Either<Resource, ResponseFormat> createResourceInstances(User user, String yamlName, Resource resource, Map<String, UploadComponentInstanceInfo> uploadResInstancesMap, boolean inTransaction, boolean needLock,
- Map<String, Resource> nodeTypeNamespaceMap) {
+ Map<String, Resource> nodeTypeNamespaceMap) {
Either<Resource, ResponseFormat> eitherResource = null;
log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName);
@@ -4114,32 +4360,36 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, refResource.getComponentType().getValue(), refResource.getName(), componentState);
return Either.right(responseFormat);
}
- ResourceTypeEnum resourceTypeEnum = refResource.getResourceType();
- if (resourceTypeEnum == ResourceTypeEnum.VF) {
- log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", resourceTypeEnum);
+
+ if (!ToscaUtils.isAtomicType(refResource) && refResource.getResourceType() != ResourceTypeEnum.CVFC) {
+ log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType());
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType());
return Either.right(responseFormat);
}
return Either.left(refResource);
}
- private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource) {
+ private Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> createResourcesInstanceInfoFromYaml(String yamlFileName, Map<String, Object> toscaJson, Resource resource, Map<String, String> createdNodesToscaResourceNames) {
Map<String, UploadComponentInstanceInfo> moduleComponentInstances = new HashMap<String, UploadComponentInstanceInfo>();
+ Map<String, Object> substitutionMappings = null;
Either<Map<String, UploadComponentInstanceInfo>, ResponseFormat> result = Either.left(moduleComponentInstances);
Either<Map<String, Object>, ResultStatusEnum> eitherNodesTemlates = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.NODE_TEMPLATES);
+ Either<Map<String, Object>, ResultStatusEnum> eitherSubstitutionMappings = ImportUtils.findFirstToscaMapElement(toscaJson, ToscaTagNamesEnum.SUBSTITUTION_MAPPINGS);
+ if (eitherSubstitutionMappings.isLeft()) {
+ substitutionMappings = eitherSubstitutionMappings.left().value();
+ }
if (eitherNodesTemlates.isLeft()) {
Map<String, Object> jsonNodeTemplates = eitherNodesTemlates.left().value();
Iterator<Entry<String, Object>> nodesNameValue = jsonNodeTemplates.entrySet().iterator();
while (nodesNameValue.hasNext()) {
Entry<String, Object> nodeNameValue = nodesNameValue.next();
- Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(nodeNameValue.getValue());
+ Either<UploadComponentInstanceInfo, ResponseFormat> eitherNode = createModuleComponentInstanceInfo(nodeNameValue, substitutionMappings, createdNodesToscaResourceNames);
if (eitherNode.isRight()) {
log.info("error when creating node template:{}, for resource:{}", nodeNameValue.getKey(), resource.getName());
return Either.right(eitherNode.right().value());
} else {
UploadComponentInstanceInfo uploadComponentInstanceInfo = eitherNode.left().value();
- uploadComponentInstanceInfo.setName(nodeNameValue.getKey());
moduleComponentInstances.put(nodeNameValue.getKey(), uploadComponentInstanceInfo);
}
@@ -4154,20 +4404,25 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return result;
}
- private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(Object nodeTemplateJson) {
+ @SuppressWarnings("unchecked")
+ private Either<UploadComponentInstanceInfo, ResponseFormat> createModuleComponentInstanceInfo(Entry<String, Object> nodeTemplateJsonEntry, Map<String, Object> substitutionMappings, Map<String, String> createdNodesToscaResourceNames) {
UploadComponentInstanceInfo nodeTemplateInfo = new UploadComponentInstanceInfo();
Either<UploadComponentInstanceInfo, ResponseFormat> result = Either.left(nodeTemplateInfo);
-
+ nodeTemplateInfo.setName(nodeTemplateJsonEntry.getKey());
try {
- if (nodeTemplateJson instanceof String) {
- String nodeTemplateJsonString = (String) nodeTemplateJson;
+ if (nodeTemplateJsonEntry.getValue() instanceof String) {
+ String nodeTemplateJsonString = (String) nodeTemplateJsonEntry.getValue();
nodeTemplateInfo.setType(nodeTemplateJsonString);
- } else if (nodeTemplateJson instanceof Map) {
- Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJson;
+ } else if (nodeTemplateJsonEntry.getValue() instanceof Map) {
+ Map<String, Object> nodeTemplateJsonMap = (Map<String, Object>) nodeTemplateJsonEntry.getValue();
// Type
if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.TYPE.getElementName())) {
- nodeTemplateInfo.setType((String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName()));
+ String toscaResourceType = (String) nodeTemplateJsonMap.get(ToscaTagNamesEnum.TYPE.getElementName());
+ if (createdNodesToscaResourceNames.containsKey(toscaResourceType)) {
+ toscaResourceType = createdNodesToscaResourceNames.get(toscaResourceType);
+ }
+ nodeTemplateInfo.setType(toscaResourceType);
}
if (nodeTemplateJsonMap.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
@@ -4195,13 +4450,30 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
nodeTemplateInfo.setProperties(regResponse.left().value());
}
}
+ if (substitutionMappings != null) {
+ if (substitutionMappings.containsKey(ToscaTagNamesEnum.CAPABILITIES.getElementName())) {
+ Either<Map<String, String>, ResponseFormat> getCapNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.CAPABILITIES.getElementName()));
+ if (getCapNamesToUpdateRes.isRight())
+ return Either.right(getCapNamesToUpdateRes.right().value());
+ if (getCapNamesToUpdateRes.left().value().size() > 0) {
+ nodeTemplateInfo.setCapabilitiesNamesToUpdate(getCapNamesToUpdateRes.left().value());
+ }
+ }
+ if (substitutionMappings.containsKey(ToscaTagNamesEnum.REQUIREMENTS.getElementName())) {
+ Either<Map<String, String>, ResponseFormat> getReqNamesToUpdateRes = getNamesToUpdate(nodeTemplateInfo, (Map<String, List<String>>) substitutionMappings.get(ToscaTagNamesEnum.REQUIREMENTS.getElementName()));
+ if (getReqNamesToUpdateRes.isRight())
+ return Either.right(getReqNamesToUpdateRes.right().value());
+ if (getReqNamesToUpdateRes.left().value().size() > 0) {
+ nodeTemplateInfo.setRequirementsNamesToUpdate(getReqNamesToUpdateRes.left().value());
+ }
+ }
+ }
} else {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE));
}
} catch (Exception e) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Import Resource - create capability");
BeEcompErrorManager.getInstance().logBeSystemError("Import Resource - create capability");
log.debug("error when creating capability, message:{}", e.getMessage(), e);
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
@@ -4210,6 +4482,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return result;
}
+ private Either<Map<String, String>, ResponseFormat> getNamesToUpdate(UploadComponentInstanceInfo nodeTemplateInfo, Map<String, List<String>> elements) {
+ Either<Map<String, String>, ResponseFormat> response;
+ try {
+ Map<String, String> namesToUpdate = elements.entrySet().stream().filter(e -> e.getValue().get(0).equalsIgnoreCase(nodeTemplateInfo.getName())).collect(Collectors.toMap(e -> e.getValue().get(1), e -> e.getKey()));
+ response = Either.left(namesToUpdate);
+ } catch (Exception e) {
+ log.debug("The exception {} occured upon adding names to update for instance {} . ", e.getMessage(), nodeTemplateInfo.getName());
+ response = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
+ }
+ return response;
+ }
+
private Either<Map<String, List<UploadPropInfo>>, ResponseFormat> createPropModuleFromYaml(Map<String, Object> nodeTemplateJsonMap) {
Map<String, List<UploadPropInfo>> moduleProp = new HashMap<String, List<UploadPropInfo>>();
Either<Map<String, List<UploadPropInfo>>, ResponseFormat> response = Either.left(moduleProp);
@@ -4222,21 +4506,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Object propValue = jsonPropObj.getValue();
if (valueContainsPattern(STR_REPLACE_PATTERN, propValue)) {
- log.debug("Ignore property value {}.", propName);
+ log.trace("Ignore property value {}.", propName);
continue;
}
if (valueContainsPattern(TOKEN_PATTERN, propValue)) {
- log.debug("Ignore property value {}.", propName);
+ log.trace("Ignore property value {}.", propName);
continue;
}
if (valueContainsPattern(GET_PROPERTY_PATTERN, propValue)) {
- log.debug("Ignore property value {}.", propName);
+ log.trace("Ignore property value {}.", propName);
continue;
}
if (valueContainsPattern(CONCAT_PATTERN, propValue)) {
- log.debug("Ignore property value {}.", propName);
+ log.trace("Ignore property value {}.", propName);
continue;
}
@@ -4399,7 +4683,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.debug("valueContainsToken value is {}", propValue);
boolean result = false;
if (propValue != null) {
- log.debug("valueContainspattern value is {}", propValue.getClass());
+ log.trace("valueContainspattern value is {}", propValue.getClass());
Matcher matcher = pattern.matcher(propValue.toString());
result = matcher.find();
}
@@ -4536,29 +4820,28 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return result;
}
- public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
+ public Either<Resource, ResponseFormat> propagateStateToCertified(User user, Resource resource, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock, boolean forceCertificationAllowed) {
+
Either<Resource, ResponseFormat> result = null;
-
- // resource updated with checkout. certify the resource
- if (resource.getLifecycleState().equals(LifecycleStateEnum.CERTIFIED)) {
- Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock);
- result = eitherPopulated.isLeft() ? Either.left(resource) : Either.right(eitherPopulated.right().value());
- return result;
- }
try {
- result = lifecycleBusinessLogic.changeState(resource.getUniqueId(), user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock);
- if (result.isLeft()) {
+ if(resource.getLifecycleState() != LifecycleStateEnum.CERTIFIED && forceCertificationAllowed){
+ result = nodeForceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
+ if(result.isRight()){
+ return result;
+ }
resource = result.left().value();
- result = lifecycleBusinessLogic.changeState(resource.getUniqueId(), user, LifeCycleTransitionEnum.START_CERTIFICATION, lifecycleChangeInfo, inTransaction, needLock);
}
- if (result.isLeft()) {
- resource = result.left().value();
- result = lifecycleBusinessLogic.changeState(resource.getUniqueId(), user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
+ if (resource.getLifecycleState() == LifecycleStateEnum.CERTIFIED) {
+ Either<Either<ArtifactDefinition, Operation>, ResponseFormat> eitherPopulated = populateToscaArtifacts(resource, user, false, inTransaction, needLock);
+ result = eitherPopulated.isLeft() ? Either.left(resource) : Either.right(eitherPopulated.right().value());
+ return result;
}
- return result;
+ return nodeFullCertification(resource.getUniqueId(), user, lifecycleChangeInfo, inTransaction, needLock);
+ } catch (Exception e) {
+ log.debug("The exception {} has occured upon certification of resource {}. ", e.getMessage(), resource.getName());
+ return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
} finally {
if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change LifecycleState - Certify");
BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
if (inTransaction == false) {
log.debug("operation failed. do rollback");
@@ -4571,6 +4854,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
+ private Either<Resource, ResponseFormat> nodeFullCertification(String uniqueId, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
+ Either<Resource, ResponseFormat> result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFICATION_REQUEST, lifecycleChangeInfo, inTransaction, needLock);
+ if (result.isLeft()) {
+ result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.START_CERTIFICATION, lifecycleChangeInfo, inTransaction, needLock);
+ }
+ if (result.isLeft()) {
+ result = lifecycleBusinessLogic.changeState(uniqueId, user, LifeCycleTransitionEnum.CERTIFY, lifecycleChangeInfo, inTransaction, needLock);
+ }
+ return result;
+ }
+
+ private Either<Resource, ResponseFormat> nodeForceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
+ return lifecycleBusinessLogic.forceResourceCertification(resource, user, lifecycleChangeInfo, inTransaction, needLock);
+ }
+
/*
* /**
*
@@ -4596,7 +4894,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
else {
StorageOperationStatus status = latestByName.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
log.debug("resource already exist {}. status={}", resource.getName(), status);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
@@ -4614,7 +4911,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// error
else {
StorageOperationStatus status = latestByName.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
@@ -4726,7 +5022,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return result;
} finally {
if (result == null || result.isRight()) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "Change LifecycleState - Certify");
BeEcompErrorManager.getInstance().logBeSystemError("Change LifecycleState - Certify");
log.debug("operation failed. do rollback");
titanDao.rollback();
@@ -4764,6 +5059,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
newResource.setVendorRelease(oldResource.getVendorRelease());
}
+ if (newResource.getResourceVendorModelNumber() == null) {
+ newResource.setResourceVendorModelNumber(oldResource.getResourceVendorModelNumber());
+ }
+
if (newResource.getContactId() == null) {
newResource.setContactId(oldResource.getContactId());
}
@@ -4808,12 +5107,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
resource.setCreatorUserId(user.getUserId());
resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
resource.setContactId(resource.getContactId().toLowerCase());
- if (resource.getResourceType().equals(ResourceTypeEnum.VF)) {
- resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(ResourceTypeEnum.VF.name(), resource.getSystemName()));
+ if (!ToscaUtils.isAtomicType(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
+ resource.setToscaResourceName(CommonBeUtils.generateToscaResourceName(resource.getResourceType().name(), resource.getSystemName()));
}
// Generate invariant UUID - must be here and not in operation since it
// should stay constant during clone
+ // TODO
String invariantUUID = UniqueIdBuilder.buildInvariantUUID();
resource.setInvariantUUID(invariantUUID);
@@ -4842,10 +5142,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Either<InterfaceDefinition, StorageOperationStatus> eitherCapTypeFound = interfaceTypeOperation.getInterface(intType);
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInterfaceMissingError, "Create Resource - validateLifecycleTypesCreate", intType);
BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateLifecycleTypesCreate", "Interface", intType);
log.debug("Lifecycle Type: {} is required by resource: {} but does not exist in the DB", intType, resource.getName());
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateLifecycleTypesCreate");
BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateLifecycleTypesCreate");
log.debug("request to data model failed with error: {}", eitherCapTypeFound.right().value().name());
}
@@ -4878,7 +5176,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (resource.getRequirements() != null && resource.getRequirements().size() > 0) {
log.debug("validate capability Types Exist - requirements section");
for (String type : resource.getRequirements().keySet()) {
- eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type) , actionEnum, eitherResult, type, inTransaction);
+ eitherResult = validateCapabilityTypeExists(user, capabilityTypeOperation, resource, resource.getRequirements().get(type), actionEnum, eitherResult, type, inTransaction);
if (eitherResult.isRight()) {
return Either.right(eitherResult.right().value());
}
@@ -4888,24 +5186,22 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return eitherResult;
}
- //@param typeObject- the object to which the validation is done
- private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List validationObjects , AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
- boolean inTransaction) {
+ // @param typeObject- the object to which the validation is done
+ private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, List validationObjects, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult, String type,
+ boolean inTransaction) {
Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(type, inTransaction);
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeCapabilityTypeMissingError, "Create Resource - validateCapabilityTypesCreate", type);
BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", type);
log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", type, resource.getName());
BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
}
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateCapabilityTypesCreate");
log.debug("Trying to get capability type {} failed with error: {}", type, eitherCapTypeFound.right().value().name());
- ResponseFormat errorResponse =null;
- if (type!=null)
+ ResponseFormat errorResponse = null;
+ if (type != null)
errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, type);
else
- errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects );
+ errorResponse = componentsUtils.getResponseFormatByElement(ActionStatus.MISSING_CAPABILITY_TYPE, validationObjects);
eitherResult = Either.right(errorResponse);
componentsUtils.auditResource(errorResponse, user, resource, "", "", actionEnum, null);
}
@@ -4913,16 +5209,14 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Either<Boolean, ResponseFormat> validateCapabilityTypeExists(User user, ICapabilityTypeOperation capabilityTypeOperation, Resource resource, AuditingActionEnum actionEnum, Either<Boolean, ResponseFormat> eitherResult,
- Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) {
+ Entry<String, List<CapabilityDefinition>> typeEntry, boolean inTransaction) {
Either<CapabilityTypeDefinition, StorageOperationStatus> eitherCapTypeFound = capabilityTypeOperation.getCapabilityType(typeEntry.getKey(), inTransaction);
if (eitherCapTypeFound.isRight()) {
if (eitherCapTypeFound.right().value() == StorageOperationStatus.NOT_FOUND) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeCapabilityTypeMissingError, "Create Resource - validateCapabilityTypesCreate", typeEntry.getKey());
BeEcompErrorManager.getInstance().logBeGraphObjectMissingError("Create Resource - validateCapabilityTypesCreate", "Capability Type", typeEntry.getKey());
log.debug("Capability Type: {} is required by resource: {} but does not exist in the DB", typeEntry.getKey(), resource.getName());
BeEcompErrorManager.getInstance().logBeDaoSystemError("Create Resource - validateCapabilityTypesCreate");
}
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Create Resource - validateCapabilityTypesCreate");
log.debug("Trying to get capability type {} failed with error: {}", typeEntry.getKey(), eitherCapTypeFound.right().value().name());
ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.MISSING_CAPABILITY_TYPE, typeEntry.getKey());
eitherResult = Either.right(errorResponse);
@@ -4985,8 +5279,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
Either<Resource, ResponseFormat> respStatus = createResourceTransaction(resource, user, isNormative, inTransaction);
if (respStatus.isLeft()) {
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
- componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, additionalParams);
+ auditCreateResource(user, respStatus.left().value(), actionEnum, additionalParams);
ASDCKpiApi.countCreatedResourcesKPI();
} else
componentsUtils.auditResource(respStatus.right().value(), user, resource, "", "", actionEnum, additionalParams);
@@ -4999,6 +5292,11 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
+ private void auditCreateResource(User user, Resource persistedResource, AuditingActionEnum actionEnum, EnumMap<AuditingFieldsKeysEnum, Object> additionalParams) {
+ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CREATED);
+ componentsUtils.auditResource(responseFormat, user, persistedResource, "", "", actionEnum, additionalParams);
+ }
+
private Either<Resource, ResponseFormat> createResourceTransaction(Resource resource, User user, boolean isNormative, boolean inTransaction) {
// validate resource name uniqueness
log.debug("validate resource name");
@@ -5026,7 +5324,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
resource.setVersion(INITIAL_VERSION);
resource.setHighestVersion(true);
- resource.setAbstract(false);
+ if (resource.getResourceType() != null && resource.getResourceType() != ResourceTypeEnum.CVFC)
+ resource.setAbstract(false);
}
Either<Resource, StorageOperationStatus> createToscaElement = toscaOperationFacade.createToscaComponent(resource);
@@ -5090,6 +5389,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
resource.setDeploymentArtifacts(artifactMap);
}
+ @SuppressWarnings("unchecked")
private void setInformationalArtifactsPlaceHolder(Resource resource, User user) {
Map<String, ArtifactDefinition> artifactMap = resource.getArtifacts();
if (artifactMap == null) {
@@ -5097,6 +5397,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
String resourceUniqueId = resource.getUniqueId();
List<String> exludeResourceCategory = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceCategory();
+ List<String> exludeResourceType = ConfigurationManager.getConfigurationManager().getConfiguration().getExcludeResourceType();
Map<String, Object> informationalResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getInformationalResourceArtifacts();
List<CategoryDefinition> categories = resource.getCategories();
boolean isCreateArtifact = true;
@@ -5110,6 +5411,16 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
+ if (isCreateArtifact && exludeResourceType != null) {
+ String resourceType = resource.getResourceType().name();
+ for (String type : exludeResourceType) {
+ if (type.equalsIgnoreCase(resourceType)) {
+ isCreateArtifact = false;
+ break;
+ }
+ }
+
+ }
if (informationalResourceArtifacts != null && isCreateArtifact) {
Set<String> keys = informationalResourceArtifacts.keySet();
@@ -5273,14 +5584,10 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
/**
* updateResourceMetadata
*
- * @param user
- * - modifier data (userId)
- * @param inTransaction
- * TODO
- * @param resourceIdToUpdate
- * - the resource identifier
+ * @param user - modifier data (userId)
+ * @param inTransaction TODO
+ * @param resourceIdToUpdate - the resource identifier
* @param newResource
- *
* @return Either<Resource, responseFormat>
*/
public Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, Resource currentResource, User user, boolean inTransaction) {
@@ -5315,7 +5622,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// lock resource
StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceIdToUpdate, NodeTypeEnum.Resource);
if (!lockResult.equals(StorageOperationStatus.OK)) {
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedLockObjectError, "Upload Artifact - lock " + resourceIdToUpdate + ": " + NodeTypeEnum.Resource);
BeEcompErrorManager.getInstance().logBeFailedLockObjectError("Upload Artifact - lock ", NodeTypeEnum.Resource.getName(), resourceIdToUpdate);
log.debug("Failed to lock resource: {}, error - {}", resourceIdToUpdate, lockResult);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockResult));
@@ -5331,7 +5637,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// list
// This code is not called from import resources, because of root
// VF "derivedFrom" should be null (or ignored)
- if (!currentResource.getResourceType().equals(ResourceTypeEnum.VF)) {
+ if (ToscaUtils.isAtomicType(currentResource)) {
Either<Boolean, ResponseFormat> derivedFromNotEmptyEither = validateDerivedFromNotEmpty(null, newResource, null);
if (derivedFromNotEmptyEither.isRight()) {
log.debug("for updated resource {}, derived from field is empty", newResource.getName());
@@ -5373,7 +5679,54 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
}
+ private Either<List<GroupDefinition>,Boolean> updateComponentGroupName(String replacePattern , String with ,List<GroupDefinition> oldGroup){
+ if ( oldGroup==null || with==null || replacePattern==null || with.isEmpty() || replacePattern.isEmpty()){
+ if (log.isInfoEnabled())
+ log.info("cannot update group name , invalid args -> replacePattern:{} , with:{} , oldGroup:{}" , replacePattern, with, oldGroup == null ? null : " < size : "+oldGroup.size()+" >" );
+ return Either.right(false);
+ }
+ List<GroupDefinition> list = oldGroup.stream().map( group -> new GroupDefinition(group)).collect(Collectors.toList());
+ for ( GroupDefinition group : list) {
+ if ( group!=null && group.isSamePrefix( replacePattern ) ){
+ String prefix = group.getName().substring( 0, replacePattern.length() );
+ String newGroupName = group.getName().replaceFirst(prefix , with);
+ group.setName(newGroupName);
+ //String newUid = group.getUniqueId().replaceFirst(prefix , with); //removing this will also change the unique id
+ //group.setUniqueId(newUid);
+ }
+ }
+ return Either.left(list);
+ }
+
+ private boolean isComponentNameChanged(Resource newResource,Resource oldResource){
+ if (newResource!=null && oldResource!=null){ //TODO - must protect all chain against null , use optional
+ String futureName = newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
+ String oldName = oldResource.getComponentMetadataDefinition().getMetadataDataDefinition().getName();
+ return !oldName.equals(futureName);
+ }
+ return false;
+ }
+
private Either<Resource, ResponseFormat> updateResourceMetadata(String resourceIdToUpdate, Resource newResource, User user, Resource currentResource, boolean shouldLock, boolean inTransaction) {
+ //region -> Update groups name for newResource
+ if ( isComponentNameChanged( currentResource , newResource) ){
+ String replacePattern = Optional.ofNullable( //get currentResource name from metadata
+ Optional.ofNullable( Optional.ofNullable( currentResource )
+ .orElse(null).getComponentMetadataDefinition() )
+ .orElse(null).getMetadataDataDefinition() )
+ .orElse(null).getName();
+ String with = Optional.ofNullable( //get newResource name from metadata
+ Optional.ofNullable( Optional.ofNullable( newResource )
+ .orElse(null).getComponentMetadataDefinition() )
+ .orElse(null).getMetadataDataDefinition() )
+ .orElse(null).getName();
+ if ( with != null && replacePattern != null ){
+ Either result = updateComponentGroupName( replacePattern , with ,currentResource.getGroups());
+ if (result.isLeft())
+ newResource.setGroups( (List<GroupDefinition>)result.left().value() );
+ }
+ }
+ //endregion
Either<Boolean, ResponseFormat> validateResourceFields = validateResourceFieldsBeforeUpdate(currentResource, newResource, inTransaction);
if (validateResourceFields.isRight()) {
@@ -5395,6 +5748,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
log.debug("send resource {} to dao for update", newResource.getUniqueId());
+ if (newResource!=null && newResource.getGroups()!=null){
+ for ( GroupDefinition group : newResource.getGroups() ){
+ if (newResource.getComponentMetadataDefinition()!=null && newResource.getComponentMetadataDefinition().getMetadataDataDefinition()!=null)
+ groupBusinessLogic.validateAndUpdateGroupMetadata(
+ newResource.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId() ,
+ user,
+ ComponentTypeEnum.RESOURCE_INSTANCE,
+ group,
+ true ,
+ false) ;
+ }
+ }
Either<Resource, StorageOperationStatus> dataModelResponse = toscaOperationFacade.updateToscaElement(newResource);
if (dataModelResponse.isRight()) {
@@ -5410,12 +5775,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
/**
* validateResourceFieldsBeforeCreate
*
- * @param user
- * - modifier data (userId)
- * @param dataModel
- * - IResourceOperation for resource crud
- * @param resource
- * - Resource object to validate
+ * @param user - modifier data (userId)
+ * @param dataModel - IResourceOperation for resource crud
+ * @param resource - Resource object to validate
* @return Either<Boolean, ErrorResponse>
*/
private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeCreate(User user, Resource resource, AuditingActionEnum actionEnum, boolean inTransaction) {
@@ -5449,7 +5811,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return eitherValidation;
}
- // validate vendor name & release
+ // validate vendor name & release & model number
log.debug("validate vendor name");
eitherValidation = validateVendorName(user, resource, actionEnum);
if (eitherValidation.isRight()) {
@@ -5462,6 +5824,12 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return eitherValidation;
}
+ log.debug("validate resource vendor model number");
+ eitherValidation = validateResourceVendorModelNumber(user, resource, actionEnum);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
// validate contact info
/*
* log.debug("validate contact info"); eitherValidation = validateContactIdContactId(user, resource, actionEnum); if (eitherValidation.isRight()) { return eitherValidation; }
@@ -5483,7 +5851,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
// validate template (derived from)
log.debug("validate derived from");
- if (resource.getResourceType().equals(ResourceTypeEnum.VF)) {
+ if (!ToscaUtils.isAtomicType(resource) && resource.getResourceType() != ResourceTypeEnum.CVFC) {
resource.setDerivedFrom(null);
}
eitherValidation = validateDerivedFromExist(user, resource, actionEnum);
@@ -5519,8 +5887,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
/**
* validateResourceFieldsBeforeUpdate
*
- * @param currentResource
- * - Resource object to validate
+ * @param currentResource - Resource object to validate
* @return Either<Boolean, ErrorResponse>
*/
private Either<Boolean, ResponseFormat> validateResourceFieldsBeforeUpdate(Resource currentResource, Resource updateInfoResource, boolean inTransaction) {
@@ -5559,6 +5926,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return eitherValidation;
}
+ log.debug("validate resource vendor model number before update");
+ eitherValidation = validateResourceVendorModelNumber(currentResource, updateInfoResource);
+ if (eitherValidation.isRight()) {
+ return eitherValidation;
+ }
+
+
log.debug("validate vendor release before update");
eitherValidation = validateVendorReleaseName(null, updateInfoResource, null);
if (eitherValidation.isRight()) {
@@ -5763,6 +6137,19 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
+ private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(Resource currentResource, Resource updateInfoResource) {
+ String updatedResourceVendorModelNumber = updateInfoResource.getResourceVendorModelNumber();
+ String currentResourceVendorModelNumber = currentResource.getResourceVendorModelNumber();
+ if (!currentResourceVendorModelNumber.equals(updatedResourceVendorModelNumber)) {
+ Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(null, updateInfoResource, null);
+ if (validateResourceVendorModelNumber.isRight()) {
+ ResponseFormat errorResponse = validateResourceVendorModelNumber.right().value();
+ return Either.right(errorResponse);
+ }
+ }
+ return Either.left(true);
+ }
+
private Either<Boolean, ResponseFormat> validateCategory(Resource currentResource, Resource updateInfoResource, boolean hasBeenCertified, boolean inTransaction) {
Either<Boolean, ResponseFormat> validateCategoryName = validateCategory(null, updateInfoResource, null, inTransaction);
if (validateCategoryName.isRight()) {
@@ -5841,9 +6228,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
log.trace("audit before sending response");
componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
return Either.right(responseFormat);
- }
-
- else if (!dataModelResponse.left().value()) {
+ } else if (!dataModelResponse.left().value()) {
log.info("resource template with name: {}, does not exists", templateName);
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.PARENT_RESOURCE_NOT_FOUND);
componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
@@ -5958,7 +6343,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
return Either.right(responseFormat);
}
if (subcategories.size() > 1) {
- log.debug("Must be only one sub ategory for resource");
+ log.debug("Must be only one sub category for resource");
ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_TOO_MUCH_SUBCATEGORIES);
return Either.right(responseFormat);
}
@@ -6071,6 +6456,18 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
+ private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(User user, Resource resource, AuditingActionEnum actionEnum) {
+ String resourceVendorModelNumber = resource.getResourceVendorModelNumber();
+ Either<Boolean, ResponseFormat> validateResourceVendorModelNumber = validateResourceVendorModelNumber(resourceVendorModelNumber);
+ if (validateResourceVendorModelNumber.isRight()) {
+ ResponseFormat responseFormat = validateResourceVendorModelNumber.right().value();
+ componentsUtils.auditResource(responseFormat, user, resource, "", "", actionEnum, null);
+ }
+ return validateResourceVendorModelNumber;
+
+ }
+
+
private Either<Boolean, ResponseFormat> validateVendorName(String vendorName) {
if (vendorName != null) {
if (!ValidationUtils.validateVendorNameLength(vendorName)) {
@@ -6091,6 +6488,26 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
+ private Either<Boolean, ResponseFormat> validateResourceVendorModelNumber(String resourceVendorModelNumber) {
+ if (resourceVendorModelNumber.equals("")) {
+ return Either.left(true);
+ } else {
+ if (!ValidationUtils.validateResourceVendorModelNumberLength(resourceVendorModelNumber)) {
+ log.info("resource vendor model number exceeds limit.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+ return Either.right(errorResponse);
+ }
+ // resource vendor model number is currently validated as vendor name
+ if (!ValidationUtils.validateVendorName(resourceVendorModelNumber)) {
+ log.info("resource vendor model number is not valid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER);
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+ }
+
+
/*
* private Either<Boolean, ResponseFormat> validateDescriptionAndCleanup(User user, Resource resource, AuditingActionEnum actionEnum) { String description = resource.getDescription(); if (!ValidationUtils.validateStringNotEmpty(description)) {
* log.debug("Resource description is empty"); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus. COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.RESOURCE.getValue()); componentsUtils.auditResource(errorResponse,
@@ -6355,7 +6772,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
if (inputs.isRight()) {
String message = "Failed when creating inputs: for resource:" + resource.getName();
BeEcompErrorManager.getInstance().logInternalFlowError("ImportResource", message, ErrorSeverity.INFO);
- Map<String, InputDefinition> resultMap = new HashMap();
+ Map<String, InputDefinition> resultMap = new HashMap<>();
return Either.left(resultMap);
}
@@ -6568,7 +6985,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
private Either<EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation(List<NonMetaArtifactInfo> artifactPathAndNameList, List<ArtifactDefinition> existingArtifactsToHandle,
- Resource resource, User user) {
+ Resource resource, User user) {
EnumMap<ArtifactOperationEnum, List<NonMetaArtifactInfo>> nodeTypeArtifactsToHandle = new EnumMap<>(ArtifactOperationEnum.class);
Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
@@ -6648,6 +7065,21 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
}
return toscaResourceName;
}
+
+ private String buildNodeToscaResourceName(String vfResourceName, String nodeTypeFullName) {
+ String toscaResourceName;
+ String nameWithouNamespacePrefix = nodeTypeFullName.substring(Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX.length());
+ String[] findTypes = nameWithouNamespacePrefix.split("\\.");
+ String resourceType = findTypes[0];
+ String actualName = nameWithouNamespacePrefix.substring(resourceType.length());
+
+ if (actualName.startsWith(Constants.ABSTRACT)) {
+ toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + ResourceTypeEnum.VFC.name().toLowerCase() + '.' + vfResourceName + '.' + actualName;
+ } else {
+ toscaResourceName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + resourceType.toLowerCase() + '.' + vfResourceName + '.' + Constants.ABSTRACT + actualName;
+ }
+ return toscaResourceName;
+ }
public ICacheMangerOperation getCacheManagerOperation() {
return cacheManagerOperation;
@@ -6659,84 +7091,13 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic {
///////////////////////////////////////// DataModel refactoring/////////////////////////////////////////////
- /*
- * /**
- *
- * @deprecated Use {@link #createOrUpdateResourceByImport(Resource,User,boolean, boolean,boolean)} instead
- */
- /*
- * public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateResourceByImport(Resource resource, User user, AuditingActionEnum auditingEnum, boolean isNormative, boolean needLock) { return
- * createOrUpdateResourceByImport(resource, user, isNormative, false, needLock); }
- */
-
- public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createOrUpdateNodeTypeByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction, boolean needLock) {
-
- // check if resource already exist
- Either<Resource, StorageOperationStatus> latestByName = toscaOperationFacade.getLatestByName(resource.getName());
- Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> result = null;
-
- // create
- if (latestByName.isRight() && latestByName.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
-
- Either<Resource, StorageOperationStatus> latestByToscaName = toscaOperationFacade.getLatestByToscaResourceName(resource.getToscaResourceName());
- if (latestByToscaName.isRight() && latestByToscaName.right().value().equals(StorageOperationStatus.NOT_FOUND))
- result = createNodeTypeByImport(resource, user, isNormative, isInTransaction);
-
- else {
- StorageOperationStatus status = latestByName.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
- BeEcompErrorManager.getInstance().logBeComponentMissingError("Create / Update resource by import", ComponentTypeEnum.RESOURCE.getValue(), resource.getName());
- log.debug("resource already exist {}. status={}", resource.getName(), status);
- ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_ALREADY_EXISTS);
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
- result = Either.right(responseFormat);
- }
-
- }
-
- // update
- else if (latestByName.isLeft()) {
- // result = updateExistingNodeTypeByImport(resource, latestByName.left().value(), user, isNormative, needLock);
- }
-
- // error
- else {
- StorageOperationStatus status = latestByName.right().value();
- BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeResourceMissingError, "Create / Update resource by import", resource.getName());
- log.debug("failed to get latest version of resource {}. status={}", resource.getName(), status);
- ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(latestByName.right().value()), resource);
- componentsUtils.auditResource(responseFormat, user, resource, "", "", AuditingActionEnum.IMPORT_RESOURCE, null);
- result = Either.right(responseFormat);
- }
- return result;
-
- }
-
- private Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> createNodeTypeByImport(Resource resource, User user, boolean isNormative, boolean isInTransaction) {
- log.debug("resource with name {} does not exist. create new resource", resource.getName());
- Either<Resource, ResponseFormat> response = validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isInTransaction);
- if (response.isRight()) {
- return Either.right(response.right().value());
- }
-
- Either<Resource, ResponseFormat> createResponse = createResourceByDao(resource, user, AuditingActionEnum.IMPORT_RESOURCE, isNormative, isInTransaction, null);
- if (createResponse.isRight()) {
- return Either.right(createResponse.right().value());
- } else {
- ImmutablePair<Resource, ActionStatus> resourcePair = new ImmutablePair<>(createResponse.left().value(), ActionStatus.CREATED);
- ASDCKpiApi.countImportResourcesKPI();
- return Either.left(resourcePair);
-
- }
- }
-
public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String resourceId, List<String> dataParamsToReturn) {
ComponentParametersView paramsToRetuen = new ComponentParametersView(dataParamsToReturn);
Either<Resource, StorageOperationStatus> resourceResultEither = toscaOperationFacade.getToscaElement(resourceId, paramsToRetuen);
if (resourceResultEither.isRight()) {
- if(resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
+ if (resourceResultEither.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
log.debug("Failed to found resource with id {} ", resourceId);
Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
}
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 b157b635b4..d2743aa039 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
@@ -124,7 +124,7 @@ public class ResourceImportManager {
lifecycleChangeInfo.setUserRemarks("certification on import");
Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
- return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null);
+ return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false);
}
public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) {
@@ -133,18 +133,18 @@ public class ResourceImportManager {
lifecycleChangeInfo.setUserRemarks("certification on import");
Function<Resource, Either<Boolean, ResponseFormat>> validator = (resource) -> resourceBusinessLogic.validatePropertiesDefaultValues(resource);
- return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null);
+ return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false);
}
public Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, Function<Resource, Either<Boolean, ResponseFormat>> validationFunction,
- LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts) {
+ LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map<ArtifactOperationEnum, List<ArtifactDefinition>> nodeTypeArtifactsToHandle, List<ArtifactDefinition> nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed) {
Resource resource = new Resource();
ImmutablePair<Resource, ActionStatus> responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED);
Either<ImmutablePair<Resource, ActionStatus>, ResponseFormat> response = Either.left(responsePair);
String latestCertifiedResourceId = null;
try {
- boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty() ? true : false;
+ boolean shouldBeCertified = nodeTypeArtifactsToHandle == null || nodeTypeArtifactsToHandle.isEmpty();
setConstantMetaData(resource, shouldBeCertified);
setMetaDataFromJson(resourceMetaData, resource);
@@ -179,7 +179,7 @@ public class ResourceImportManager {
}
}
latestCertifiedResourceId = getLatestCertifiedResourceId(resource);
- changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock);
+ changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed);
if (changeStateResponse.isRight()) {
response = Either.right(changeStateResponse.right().value());
} else {
@@ -270,14 +270,14 @@ public class ResourceImportManager {
}
- private Either<Boolean, ResponseFormat> populateResourceFromYaml(String resourceYml, Resource resource, boolean inTransaction) {
+ Either<Boolean, ResponseFormat> populateResourceFromYaml(String resourceYml, Resource resource, boolean inTransaction) {
@SuppressWarnings("unchecked")
Either<Boolean, ResponseFormat> eitherResult = Either.left(true);
Map<String, Object> toscaJsonAll = (Map<String, Object>) new Yaml().load(resourceYml);
Map<String, Object> toscaJson = toscaJsonAll;
// Checks if exist and builds the node_types map
- if (toscaJsonAll.containsKey(ToscaTagNamesEnum.NODE_TYPES.getElementName())) {
+ if (toscaJsonAll.containsKey(ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType()!=ResourceTypeEnum.CVFC) {
toscaJson = new HashMap<String, Object>();
toscaJson.put(ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(ToscaTagNamesEnum.NODE_TYPES.getElementName()));
}
@@ -721,7 +721,7 @@ public class ResourceImportManager {
capabilityDefinition.setProperties(capabilityProperties);
}
}
- } else {
+ } else if (!(capabilityJson instanceof List)) {
result = Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML));
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 bc1c6e5910..ae7ae31ed9 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
@@ -447,14 +447,12 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return componentsFieldsValidation;
}
- // validate service name uniqueness
log.debug("validate service name uniqueness");
Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, service, actionEnum);
if (serviceNameUniquenessValidation.isRight()) {
return serviceNameUniquenessValidation;
}
- // validate category
log.debug("validate category");
Either<Boolean, ResponseFormat> categoryValidation = validateServiceCategory(user, service, actionEnum);
if (categoryValidation.isRight()) {
@@ -462,12 +460,23 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
// validate project name (ProjectCode) - mandatory in service
-
log.debug("validate projectName");
Either<Boolean, ResponseFormat> projectCodeValidation = validateProjectCode(user, service, actionEnum);
if (projectCodeValidation.isRight()) {
return projectCodeValidation;
}
+
+ log.debug("validate service type");
+ Either<Boolean, ResponseFormat> serviceTypeValidation = validateServiceTypeAndCleanup(user, service, actionEnum);
+ if (serviceTypeValidation.isRight()) {
+ return serviceTypeValidation;
+ }
+
+ log.debug("validate service role");
+ Either<Boolean, ResponseFormat> serviceRoleValidation = validateServiceRoleAndCleanup(user, service, actionEnum);
+ if (serviceRoleValidation.isRight()) {
+ return serviceRoleValidation;
+ }
return Either.left(true);
@@ -704,6 +713,18 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
if (!uuidCurrent.equals(uuidUpdated)) {
log.info("update srvice: recived request to update uuid to {} the field is not updatable ignoring.", uuidUpdated);
}
+
+ response = validateAndUpdateServiceType(user, currentService, serviceUpdate, null);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
+
+ response = validateAndUpdateServiceRole(user, currentService, serviceUpdate, null);
+ if (response.isRight()) {
+ ResponseFormat errorResponse = response.right().value();
+ return Either.right(errorResponse);
+ }
String currentInvariantUuid = currentService.getInvariantUUID();
String updatedInvariantUuid = serviceUpdate.getInvariantUUID();
@@ -821,18 +842,18 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
return Either.left(true);
}
- private Either<Boolean, ResponseFormat> validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
+ private Either<Boolean, ResponseFormat> validateAndUpdateServiceName(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum auditingAction) {
String serviceNameUpdated = serviceUpdate.getName();
String serviceNameCurrent = currentService.getName();
if (!serviceNameCurrent.equals(serviceNameUpdated)) {
if (!hasBeenCertified) {
- Either<Boolean, ResponseFormat> validatServiceNameResponse = validateComponentName(user, serviceUpdate, audatingAction);
+ Either<Boolean, ResponseFormat> validatServiceNameResponse = validateComponentName(user, serviceUpdate, auditingAction);
if (validatServiceNameResponse.isRight()) {
ResponseFormat errorRespons = validatServiceNameResponse.right().value();
return Either.right(errorRespons);
}
- Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, serviceUpdate, audatingAction);
+ Either<Boolean, ResponseFormat> serviceNameUniquenessValidation = validateComponentNameUnique(user, serviceUpdate, auditingAction);
if (serviceNameUniquenessValidation.isRight()) {
return serviceNameUniquenessValidation;
}
@@ -848,6 +869,111 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
}
return Either.left(true);
}
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateServiceType(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) {
+ String updatedServiceType = updatedService.getServiceType();
+ String currentServiceType = currentService.getServiceType();
+ if (!currentServiceType.equals(updatedServiceType)) {
+ Either<Boolean, ResponseFormat> validateServiceType = validateServiceTypeAndCleanup(user, updatedService , auditingAction);
+ if (validateServiceType.isRight()) {
+ ResponseFormat errorResponse = validateServiceType.right().value();
+ componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, "", "", auditingAction, ComponentTypeEnum.SERVICE);
+ return Either.right(errorResponse);
+ }
+ currentService.setServiceType(updatedServiceType);
+ }
+ return Either.left(true);
+ }
+
+ protected Either<Boolean, ResponseFormat> validateServiceTypeAndCleanup(User user, Component component, AuditingActionEnum actionEnum) {
+ String serviceType = ((Service)component).getServiceType();
+ if (serviceType != null){
+ serviceType = cleanUpText(serviceType);
+ Either<Boolean, ResponseFormat> validateServiceType = validateServiceType(serviceType);
+ if (validateServiceType.isRight()) {
+ ResponseFormat responseFormat = validateServiceType.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, ComponentTypeEnum.SERVICE);
+ return Either.right(responseFormat);
+ }
+ return Either.left(true);
+ } else {
+ return Either.left(false);
+ }
+ }
+
+
+ private Either<Boolean, ResponseFormat> validateServiceType(String serviceType) {
+ if (serviceType.equals("")){
+ return Either.left(true);
+ } else {
+ if (!ValidationUtils.validateServiceTypeLength(serviceType)) {
+ log.info("service type exceeds limit.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_TYPE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_TYPE_MAX_LENGTH);
+ return Either.right(errorResponse);
+ }
+
+ if (!ValidationUtils.validateIsEnglish(serviceType)) {
+ log.info("service type is not valid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_TYPE);
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+ }
+
+ private Either<Boolean, ResponseFormat> validateAndUpdateServiceRole(User user, Service currentService, Service updatedService, AuditingActionEnum auditingAction) {
+ String updatedServiceRole = updatedService.getServiceRole();
+ String currentServiceRole = currentService.getServiceRole();
+ if (!currentServiceRole.equals(updatedServiceRole)) {
+ Either<Boolean, ResponseFormat> validateServiceRole = validateServiceRoleAndCleanup(user, updatedService , auditingAction);
+ if (validateServiceRole.isRight()) {
+ ResponseFormat errorResponse = validateServiceRole.right().value();
+ componentsUtils.auditComponentAdmin(errorResponse, user, updatedService, "", "", auditingAction, ComponentTypeEnum.SERVICE);
+ return Either.right(errorResponse);
+ }
+ currentService.setServiceRole(updatedServiceRole);
+ }
+ return Either.left(true);
+ }
+
+ protected Either<Boolean, ResponseFormat> validateServiceRoleAndCleanup(User user, Component component, AuditingActionEnum actionEnum) {
+ String serviceRole = ((Service)component).getServiceRole();
+ if (serviceRole != null){
+ serviceRole = cleanUpText(serviceRole);
+
+ Either<Boolean, ResponseFormat> validateServiceRole = validateServiceRole(serviceRole);
+ if (validateServiceRole.isRight()) {
+ ResponseFormat responseFormat = validateServiceRole.right().value();
+ componentsUtils.auditComponentAdmin(responseFormat, user, component, "", "", actionEnum, ComponentTypeEnum.SERVICE);
+ return Either.right(responseFormat);
+ }
+ return Either.left(true);
+ } else {
+ return Either.left(false);
+ }
+ }
+
+
+ private Either<Boolean, ResponseFormat> validateServiceRole(String serviceRole) {
+ if (serviceRole.equals("")){
+ return Either.left(true);
+ } else {
+ if (!ValidationUtils.validateServiceRoleLength(serviceRole)) {
+ log.info("service role exceeds limit.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.SERVICE_ROLE_EXCEEDS_LIMIT, "" + ValidationUtils.SERVICE_ROLE_MAX_LENGTH);
+ return Either.right(errorResponse);
+ }
+
+ if (!ValidationUtils.validateIsEnglish(serviceRole)) {
+ log.info("service role is not valid.");
+ ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_ROLE);
+ return Either.right(errorResponse);
+ }
+ return Either.left(true);
+ }
+ }
+
+
private Either<Boolean, ResponseFormat> validateAndUpdateCategory(User user, Service currentService, Service serviceUpdate, boolean hasBeenCertified, AuditingActionEnum audatingAction) {
List<CategoryDefinition> categoryUpdated = serviceUpdate.getCategories();
@@ -1225,7 +1351,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic {
// DE194021
ServletContext servletContext = request.getSession().getServletContext();
- boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(request.getSession().getServletContext()); // DE
+ boolean isDistributionEngineUp = getHealthCheckBL(servletContext).isDistributionEngineUp(); // DE
if (!isDistributionEngineUp) {
BeEcompErrorManager.getInstance().logBeSystemError("Distribution Engine is DOWN");
log.debug("Distribution Engine is DOWN");
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 9586be81ea..11ffcd9329 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
@@ -31,10 +31,6 @@ import fj.data.Either;
@Component("serviceComponentInstanceBusinessLogic")
public class ServiceComponentInstanceBusinessLogic extends ComponentInstanceBusinessLogic {
- @Override
- protected Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances(org.openecomp.sdc.be.model.Component containerComponent) {
- return Either.left(true);
- }
@Override
protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java
index 61a5af5b74..5a93ecf182 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/VFComponentInstanceBusinessLogic.java
@@ -25,6 +25,7 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.tosca.ToscaUtils;
import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -38,17 +39,6 @@ public class VFComponentInstanceBusinessLogic extends ComponentInstanceBusinessL
private static Logger log = LoggerFactory.getLogger(VFComponentInstanceBusinessLogic.class.getName());
@Override
- protected Either<Boolean, ResponseFormat> validateAllowedToContainCompInstances(org.openecomp.sdc.be.model.Component containerComponent) {
- Resource resource = (Resource) containerComponent;
- ResourceTypeEnum resourceType = resource.getResourceType();
- if (ResourceTypeEnum.VF != resourceType) {
- log.debug("Cannot attach resource instances to container resource of type {}", resourceType);
- return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, resourceType.getValue()));
- }
- return Either.left(true);
- }
-
- @Override
protected NodeTypeEnum getNodeTypeOfComponentInstanceOrigin() {
return NodeTypeEnum.Resource;
}
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 042af54383..b18c4d0985 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
@@ -55,6 +55,7 @@ import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.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;
@@ -66,6 +67,7 @@ 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;
@@ -196,7 +198,7 @@ public class CertificationRequestTransition extends LifeCycleTransition {
ResponseFormat responseFormat;
Either<? extends Component, ResponseFormat> result = null;
try{
- if (componentType == ComponentTypeEnum.SERVICE || (componentType == ComponentTypeEnum.RESOURCE && ((Resource) component).getResourceType() == ResourceTypeEnum.VF)) {
+ if (component.getToscaType().equals(ToscaElementTypeEnum.TopologyTemplate.getValue())) {
Either<Boolean, ResponseFormat> statusCert = validateAllResourceInstanceCertified(component);
if (statusCert.isRight()) {
@@ -270,7 +272,10 @@ public class CertificationRequestTransition extends LifeCycleTransition {
// occurrences in the future
Map<String, List<String>> reqName2Ids = new HashMap<>();
Map<String, List<String>> capName2Ids = new HashMap<>();
- parseRelationsForReqCapVerification(component, reqName2Ids, capName2Ids);
+// Either<Boolean, ResponseFormat> parseRelationsForReqCapVerificationRes = parseRelationsForReqCapVerification(component, reqName2Ids, capName2Ids);
+// if(parseRelationsForReqCapVerificationRes.isRight()){
+// return parseRelationsForReqCapVerificationRes;
+// }
Map<String, Set<String>> requirementsToFulfillBeforeCert = configurationManager.getConfiguration().getRequirementsToFulfillBeforeCert();
Map<String, Set<String>> capabilitiesToConsumeBeforeCert = configurationManager.getConfiguration().getCapabilitiesToConsumeBeforeCert();
for (ComponentInstance compInst : componentInstances) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java
index 8e89a6bf31..4fe0965ef6 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/lifecycle/LifecycleBusinessLogic.java
@@ -32,6 +32,7 @@ import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
import org.openecomp.sdc.be.components.impl.ProductBusinessLogic;
import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
+import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
@@ -46,13 +47,14 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.jsontitan.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.ICacheMangerOperation;
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.CapabilityOperation;
-import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.be.tosca.ToscaExportHandler;
import org.openecomp.sdc.common.api.Constants;
@@ -204,9 +206,9 @@ public class LifecycleBusinessLogic {
String resourceCurrVersion = component.getVersion();
LifecycleStateEnum resourceCurrState = component.getLifecycleState();
- log.info("lock component {}", componentId);
// lock resource
if (inTransaction == false && needLock) {
+ log.info("lock component {}", componentId);
Either<Boolean, ResponseFormat> eitherLockResource = lockComponent(componentType, component);
if (eitherLockResource.isRight()) {
errorResponse = eitherLockResource.right().value();
@@ -214,8 +216,8 @@ public class LifecycleBusinessLogic {
log.error("lock component {} failed", componentId);
return Either.right(errorResponse);
}
+ log.info("after lock component {}", componentId);
}
- log.info("after lock component {}", componentId);
try {
Either<String, ResponseFormat> commentValidationResult = validateComment(changeInfo, transitionEnum);
if (commentValidationResult.isRight()) {
@@ -463,4 +465,51 @@ public class LifecycleBusinessLogic {
return Either.left(latestComponent);
}
+ public Either<Resource, ResponseFormat> forceResourceCertification(Resource resource, User user, LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean inTransaction, boolean needLock) {
+ Either<Resource, ResponseFormat> result = null;
+ Either<ToscaElement, StorageOperationStatus> certifyResourceRes = null;
+ if(lifecycleChangeInfo.getAction() != LifecycleChanceActionEnum.CREATE_FROM_CSAR){
+ log.debug("Force certification is not allowed for the action {}. ", lifecycleChangeInfo.getAction().name());
+ result = Either.right(componentUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
+ }
+ // lock resource
+ if(result == null && !inTransaction && needLock){
+ log.info("lock component {}", resource.getUniqueId());
+ Either<Boolean, ResponseFormat> eitherLockResource = lockComponent(resource.getComponentType(), resource);
+ if (eitherLockResource.isRight()) {
+ log.error("lock component {} failed", resource.getUniqueId());
+ result = Either.right(eitherLockResource.right().value());
+ }
+ log.info("after lock component {}", resource.getUniqueId());
+ }
+ try{
+ if(result == null){
+ certifyResourceRes = lifecycleOperation.forceCerificationOfToscaElement(resource.getUniqueId(), user.getUserId(), user.getUserId());
+ if (certifyResourceRes.isRight()) {
+ StorageOperationStatus status = certifyResourceRes.right().value();
+ log.debug("Failed to perform a force certification of resource {}. The status is {}. ", resource.getName(), status);
+ result = Either.right(componentUtils.getResponseFormatByResource(componentUtils.convertFromStorageResponse(status), resource));
+ }
+ }
+ if(result == null){
+ result = Either.left(ModelConverter.convertFromToscaElement(certifyResourceRes.left().value()));
+ }
+ } finally {
+ log.info("unlock component {}", resource.getUniqueId());
+ if (!inTransaction) {
+ if(result.isLeft()){
+ titanDao.commit();
+ } else{
+ titanDao.rollback();
+ }
+ if(needLock){
+ NodeTypeEnum nodeType = resource.getComponentType().getNodeType();
+ log.info("During change state, another component {} has been created/updated", resource.getUniqueId());
+ graphLockOperation.unlockComponent(resource.getUniqueId(), nodeType);
+ }
+ }
+ }
+ return result;
+ }
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java
index c3708d4017..f96e226d26 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/AssetsDataServlet.java
@@ -126,10 +126,11 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
Response response = null;
ResponseFormat responseFormat = null;
String query = request.getQueryString();
- String requestURI = request.getRequestURI();
+ String requestURI = request.getRequestURI().endsWith("/")?
+ removeDuplicateSlashSeparator(request.getRequestURI()): request.getRequestURI();
String url = request.getMethod() + " " + requestURI;
log.debug("Start handle request of {}", url);
-
+
AuditingActionEnum auditingActionEnum = query == null ? AuditingActionEnum.GET_ASSET_LIST : AuditingActionEnum.GET_FILTERED_ASSET_LIST;
EnumMap<AuditingFieldsKeysEnum, Object> additionalParam = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
@@ -162,7 +163,7 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
}
if (resourceType != null) {
ResourceTypeEnum resourceTypeEnum = ResourceTypeEnum.getTypeIgnoreCase(resourceType);
- if( resourceTypeEnum == null ){
+ if (resourceTypeEnum == null) {
log.debug("getAssetList: Asset Fetching Failed. Invalid resource type was received");
responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT);
getComponentsUtils().auditExternalGetAsset(responseFormat, auditingActionEnum, additionalParam);
@@ -370,4 +371,11 @@ public class AssetsDataServlet extends AbstractValidationsServlet {
return response;
}
}
+
+
+ private String removeDuplicateSlashSeparator(String requestUri) {
+ return requestUri.substring(0, requestUri.length()-1);
+ }
+
+
}
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java
index b4240777a8..40a5322afa 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/CrudExternalServlet.java
@@ -120,7 +120,7 @@ public class CrudExternalServlet extends AbstractValidationsServlet {
@ApiOperation(value = "creates a resource", httpMethod = "POST", notes = "Creates a resource")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "ECOMP component is authenticated and Asset created", response = Resource.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"),
@ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
@ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
@ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
@@ -269,7 +269,7 @@ public class CrudExternalServlet extends AbstractValidationsServlet {
@ApiOperation(value = "Change Resource lifecycle State", httpMethod = "POST")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Resource state changed", response = AssetMetadata.class),
- @ApiResponse(code = 400, message = "Missing 'X-ECOMP-InstanceID' HTTP header - POL5001"),
+ @ApiResponse(code = 400, message = "Missing X-ECOMP-InstanceID HTTP header - POL5001"),
@ApiResponse(code = 401, message = "ECOMP component should authenticate itself and to re-send again HTTP request with its Basic Authentication credentials - POL5002"),
@ApiResponse(code = 403, message = "ECOMP component is not authorized - POL5003"),
@ApiResponse(code = 404, message = "Error: Requested '%1' (uuid) resource was not found - SVC4063"),
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java
index 92bc31f123..dff6cddbbb 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentServlet.java
@@ -120,7 +120,7 @@ public class ComponentServlet extends BeGenericServlet {
@Path("/{componentType}/{componentId}/requirmentsCapabilities")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirments And Capabilities according to componentId", response = Resource.class)
+ @ApiOperation(value = "Get Component Requirments And Capabilities", httpMethod = "GET", notes = "Returns Requirements And Capabilities according to componentId", response = Resource.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") })
public Response getRequirementAndCapabilities(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request,
@HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java
index da64dc58fb..4b2ff89ef8 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ElementServlet.java
@@ -20,26 +20,8 @@
package org.openecomp.sdc.be.servlets;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.inject.Singleton;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
+import com.jcabi.aspects.Loggable;
+import fj.data.Either;
import org.openecomp.sdc.be.components.clean.ComponentsCleanBusinessLogic;
import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
@@ -47,13 +29,9 @@ import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
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.info.ArtifactTypesInfo;
-import org.openecomp.sdc.be.model.ArtifactType;
-import org.openecomp.sdc.be.model.Category;
-import org.openecomp.sdc.be.model.Component;
-import org.openecomp.sdc.be.model.PropertyScope;
-import org.openecomp.sdc.be.model.Tag;
-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.GroupingDefinition;
import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
@@ -65,14 +43,20 @@ import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.jcabi.aspects.Loggable;
+import javax.inject.Singleton;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
-import fj.data.Either;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.*;
@Path("/v1/")
@@ -552,14 +536,14 @@ public class ElementServlet extends BeGenericServlet {
@ApiOperation(value = "Retrieve catalog resources and services", httpMethod = "GET", notes = "Retrieve catalog resources and services", response = User.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Returns resources and services Ok"), @ApiResponse(code = 404, message = "No resources and services were found"), @ApiResponse(code = 404, message = "User not found"),
@ApiResponse(code = 500, message = "Internal Server Error") })
- public Response getCatalogComponents(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
+ public Response getCatalogComponents(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @QueryParam("excludeTypes") List<OriginTypeEnum> excludeTypes) {
Response res = null;
try {
String url = request.getMethod() + " " + request.getRequestURI();
log.debug("Start handle request of {}", url);
- Either<Map<String, List<? extends Component>>, ResponseFormat> catalogData = getElementBL(request.getSession().getServletContext()).getCatalogComponents(userId);
+ Either<Map<String, List<? extends Component>>, ResponseFormat> catalogData = getElementBL(request.getSession().getServletContext()).getCatalogComponents(userId, excludeTypes);
if (catalogData.isRight()) {
log.debug("failed to get catalog data");
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java
index 04081bac30..f7e7ae2da1 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/GroupServlet.java
@@ -153,7 +153,7 @@ public class GroupServlet extends AbstractValidationsServlet {
// Update GroupDefinition
ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
Either<GroupDefinition, ResponseFormat> actionResponse = businessLogic
- .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true);
+ .validateAndUpdateGroupMetadata(componentId, user, componentTypeEnum, updatedGroup, true ,true);
if (actionResponse.isRight()) {
log.debug("failed to update GroupDefinition");
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 fb87e34de7..b70dae68e8 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
@@ -75,8 +75,10 @@ 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;
+import org.openecomp.sdc.be.utils.CommonBeUtils;
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.impl.ExternalConfiguration;
import org.openecomp.sdc.common.util.GeneralUtility;
import org.openecomp.sdc.common.util.ValidationUtils;
@@ -146,9 +148,14 @@ public class CsarUtils {
"([\\w\\_\\-\\.\\s]+)(/)" +
// Artifact Type
"([\\w\\_\\-\\.\\s]+)(/)" +
- // Artifact File Name
- "([\\w\\_\\-\\.\\s]+)";
- public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
+ // Artifact Any File Name
+ ".+";
+ public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)";
+ public static final String SERVICE_TEMPLATE_PATH_PATTERN = Constants.SERVICE_TEMPLATES_CONTAINING_FOLDER +
+ // Service Template File Name
+ "([\\w\\_\\-\\.\\s]+)";
+
+ public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
public CsarUtils() {
if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){
@@ -281,8 +288,8 @@ public class CsarUtils {
dependencies = dependenciesRes.left().value().getDependencies();
}
- //UID <cassandraId,filename,component>
- Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>();
+ //UID <cassandraId,filename,component>
+ Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>();
if (dependencies != null && !dependencies.isEmpty()) {
for (Triple<String, String, Component> d : dependencies) {
@@ -295,18 +302,16 @@ public class CsarUtils {
return Either.right(responseFormat);
}
- //fill innerComponentsCache
- fileName = d.getLeft();
- innerComponentsCache.put(childComponent.getUniqueId(),
- new ImmutableTriple<String, String, Component>(cassandraId, fileName, childComponent));
- insertInnerComponentsToCache(innerComponentsCache, childComponent);
-
- byte[] content = entryData.left().value();
- generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content));
- }
+ //fill innerComponentsCache
+ fileName = d.getLeft();
+ addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent);
+ addInnerComponentsToCache(innerComponentsCache, childComponent);
- //add inner components to CSAR
-
+ byte[] content = entryData.left().value();
+ generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content));
+ }
+
+ //add inner components to CSAR
for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache.entrySet()) {
ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue();
@@ -418,7 +423,7 @@ public class CsarUtils {
}
- private void insertInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
+ private void addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
Component childComponent) {
List<ComponentInstance> instances = childComponent.getComponentInstances();
@@ -438,19 +443,32 @@ public class CsarUtils {
ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
if (childArtifactDefinition != null) {
//add to cache
- componentCache.put(ci.getComponentUid(),
- new ImmutableTriple<String, String, Component>(childArtifactDefinition.getEsId(),
- childArtifactDefinition.getArtifactName(), componentRI));
+ addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI);
}
//if not atomic - insert inner components as well
if(!ToscaUtils.isAtomicType(componentRI)) {
- insertInnerComponentsToCache(componentCache, componentRI);
+ addInnerComponentsToCache(componentCache, componentRI);
}
}
});
}
}
+
+ private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
+ String id, String fileName, Component component) {
+
+ ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID());
+ if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) {
+ componentCache.put(component.getInvariantUUID(),
+ new ImmutableTriple<String, String, Component>(id, fileName, component));
+
+ if(cachedComponent != null) {
+ //overwriting component with newer version
+ log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion());
+ }
+ }
+ }
private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, String fileName) {
try {
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 0804ef1ed4..b8414367aa 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
@@ -100,7 +100,7 @@ public class PropertyConvertor {
eschema.setDescription(schema.getProperty().getDescription());
prop.setEntry_schema(eschema);
}
- log.debug("try to convert property {} from type {} with default value {}", property.getName(), property.getType(), property.getDefaultValue());
+ 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.setType(property.getType());
prop.setDescription(property.getDescription());
@@ -112,45 +112,46 @@ public class PropertyConvertor {
}
public Object convertToToscaObject(String propertyType, String propertyName, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) {
- log.debug("try to convert propertyType {} , value {}, innerType {}", propertyType, value, innerType);
+ log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType);
if (value == null) {
value = getDataTypeDefaultValue(propertyName, dataTypes.get(propertyType));
if(StringUtils.isEmpty(value)){
return null;
}
- }
-
- ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance();
- ToscaValueConverter innerConverter = null;
- Boolean isScalar = true;
-
- ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
- if (type == null) {
- log.debug("isn't prederfined type, get from all data types");
- DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
- if (innerType == null) {
- innerType = propertyType;
- }
-
- if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) {
- log.debug("This is scalar type. get suitable converter for type {}", type);
- innerConverter = type.getValueConverter();
- } else {
- isScalar = false;
- }
- } else {
- ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType());
- if (typeIfScalar == null) {
- isScalar = false;
- }
- innerConverter = type.getValueConverter();
- if (ToscaPropertyType.STRING.equals(type) && value.startsWith("/")) {
- return innerConverter.convertToToscaValue(value, innerType, dataTypes);
- }
}
- JsonElement jsonElement = null;
try {
+ ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance();
+ ToscaValueConverter innerConverter = null;
+ Boolean isScalar = true;
+
+ ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
+ if (type == null) {
+ log.trace("isn't prederfined type, get from all data types");
+ DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType);
+ if (innerType == null) {
+ innerType = propertyType;
+ }
+
+ if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) {
+ log.trace("This is scalar type. get suitable converter for type {}", type);
+ innerConverter = type.getValueConverter();
+ } else {
+ isScalar = false;
+ }
+ } else {
+ ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType());
+ if (typeIfScalar == null) {
+ isScalar = false;
+ }
+
+ innerConverter = type.getValueConverter();
+ if (ToscaPropertyType.STRING.equals(type) && value.startsWith("/")) {
+ return innerConverter.convertToToscaValue(value, innerType, dataTypes);
+ }
+ }
+ JsonElement jsonElement = null;
+
StringReader reader = new StringReader(value);
JsonReader jsonReader = new JsonReader(reader);
jsonReader.setLenient(true);
@@ -162,11 +163,11 @@ public class PropertyConvertor {
}
if (jsonElement.isJsonPrimitive() && isScalar) {
- log.debug("It's well defined type. convert it");
+ log.trace("It's well defined type. convert it");
ToscaValueConverter converter = type.getValueConverter();
return converter.convertToToscaValue(value, innerType, dataTypes);
} else {
- log.debug("It's data type or inputs in primitive type. convert as map");
+ log.trace("It's data type or inputs in primitive type. convert as map");
Object convertedValue;
if (innerConverter != null && (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(type))) {
convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes);
@@ -185,7 +186,7 @@ public class PropertyConvertor {
return convertedValue;
}
- } catch (JsonSyntaxException e) {
+ } catch (Exception e) {
log.debug("convertToToscaValue failed to parse json value :", e);
return null;
}
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 d6f87967ca..9fdd2d3b0f 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
@@ -333,10 +333,13 @@ public class ToscaExportHandler {
toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName());
toscaMetadata.setResourceVendor(resource.getVendorName());
toscaMetadata.setResourceVendorRelease(resource.getVendorRelease());
-
+ toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber());
break;
case SERVICE:
+ Service service = (Service) component;
toscaMetadata.setType(component.getComponentType().getValue());
+ toscaMetadata.setServiceType(service.getServiceType());
+ toscaMetadata.setServiceRole(service.getServiceRole());
if (!isInstance) {
// DE268546
toscaMetadata.setServiceEcompNaming(((Service)component).isEcompGeneratedNaming());
@@ -747,8 +750,9 @@ public class ToscaExportHandler {
toscaMetadata = new VfModuleToscaMetadata();
Map<String, Object> properties = fillGroupProperties(props.get());
-
- properties.put(VF_MODULE_DESC_KEY, description.get());
+ if(!properties.containsKey(VF_MODULE_DESC_KEY) || StringUtils.isEmpty((String) properties.get(VF_MODULE_DESC_KEY))){
+ properties.put(VF_MODULE_DESC_KEY, description.get());
+ }
toscaGroup.setProperties(properties);
}
toscaMetadata.setName(groupName.get());
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java
index 6573313dbb..604a52083b 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java
@@ -32,6 +32,9 @@ public class ToscaMetadata implements IToscaMetadata {
private String subcategory;
private String resourceVendor;
private String resourceVendorRelease;
+ private String resourceVendorModelNumber;
+ private String serviceType;
+ private String serviceRole;
private Boolean serviceEcompNaming;
private Boolean ecompGeneratedNaming;
private String namingPolicy;
@@ -110,6 +113,30 @@ public class ToscaMetadata implements IToscaMetadata {
public void setResourceVendorRelease(String resourceVendorRelease) {
this.resourceVendorRelease = resourceVendorRelease;
}
+
+ public String getResourceVendorModelNumber() {
+ return resourceVendorModelNumber;
+ }
+
+ public void setResourceVendorModelNumber(String resourceVendorModelNumber) {
+ this.resourceVendorModelNumber = resourceVendorModelNumber;
+ }
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public String getServiceRole() {
+ return serviceRole;
+ }
+
+ public void setServiceRole(String serviceRole) {
+ this.serviceRole = serviceRole;
+ }
public Boolean isEcompGeneratedNaming() {
return ecompGeneratedNaming;
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java
index 99e0da0116..7485a8dc43 100644
--- a/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java
+++ b/catalog-be/src/main/java/org/openecomp/sdc/common/transaction/mngr/RollbackManager.java
@@ -20,20 +20,20 @@
package org.openecomp.sdc.common.transaction.mngr;
-import org.openecomp.sdc.common.transaction.api.RollbackHandler;
-import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum;
-import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum;
-import org.openecomp.sdc.common.util.MethodActivationStatusEnum;
-
import fj.P;
import fj.data.Either;
import fj.data.HashMap;
import fj.data.List;
+import org.openecomp.sdc.common.transaction.api.RollbackHandler;
+import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBActionCodeEnum;
+import org.openecomp.sdc.common.transaction.api.TransactionUtils.DBTypeEnum;
+import org.openecomp.sdc.common.util.MethodActivationStatusEnum;
+
public class RollbackManager {
private final HashMap<DBTypeEnum, RollbackHandler> rollbackHandlersMap;
private final Integer transactionId;
- private final String userId;
+ private final String userId;
private final String actionType;
RollbackManager(Integer transactionId, String userId, String actionType, Iterable<RollbackHandler> rollbackHandlers) {
@@ -83,5 +83,4 @@ public class RollbackManager {
// by convention left is failure; in SDC right is failure
return rollbackHandlersMap.get(dbType).toEither(MethodActivationStatusEnum.NOT_FOUND).swap();
}
-
}
diff --git a/catalog-be/src/main/resources/config/SDC.zip b/catalog-be/src/main/resources/config/SDC.zip
index 674f6f86b4..6df1b13f2b 100644
--- a/catalog-be/src/main/resources/config/SDC.zip
+++ b/catalog-be/src/main/resources/config/SDC.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/config/configuration.yaml b/catalog-be/src/main/resources/config/configuration.yaml
index c9ebfd2e9f..bbb1969255 100644
--- a/catalog-be/src/main/resources/config/configuration.yaml
+++ b/catalog-be/src/main/resources/config/configuration.yaml
@@ -23,7 +23,7 @@ beSslPort: 8443
version: 1.0
released: 2012-11-30
-toscaConformanceLevel: 3.0
+toscaConformanceLevel: 4.0
minToscaConformanceLevel: 3.0
titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties
@@ -41,7 +41,6 @@ esReconnectIntervalInSeconds: 3
uebHealthCheckReconnectIntervalInSeconds: 15
uebHealthCheckReadTimeout: 4
-
# Protocols
protocols:
- http
@@ -75,7 +74,7 @@ neo4j:
cassandraConfig:
cassandraHosts: ['localhost']
- localDataCenter:
+ localDataCenter: datacenter1
reconnectTimeout : 30000
authenticate: false
username: koko
@@ -87,6 +86,7 @@ cassandraConfig:
- { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- { name: sdccomponent, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+ - { name: sdcrepository, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
#Application-specific settings of ES
elasticSearch:
@@ -147,6 +147,7 @@ resourceTypes: &allResourceTypes
- VF
- VFCMT
- Abstract
+ - CVFC
# validForResourceTypes usage
# validForResourceTypes:
@@ -195,6 +196,8 @@ toscaArtifacts:
#Informational artifacts placeHolder
excludeResourceCategory:
- Generic
+excludeResourceType:
+ - PNF
informationalResourceArtifacts:
features:
displayName: Features
@@ -500,7 +503,15 @@ resourceInformationalArtifacts:
validForResourceTypes: *allResourceTypes
OTHER:
acceptedTypes:
- validForResourceTypes: *allResourceTypes
+ validForResourceTypes:
+ - VFC
+ - CVFC
+ - CP
+ - VL
+ - VF
+ - VFCMT
+ - Abstract
+ - PNF
SNMP_POLL:
acceptedTypes:
validForResourceTypes: *allResourceTypes
@@ -512,6 +523,7 @@ resourceInformationalArtifacts:
validForResourceTypes:
- VF
- VFC
+ - CVFC
resourceInformationalDeployedArtifacts:
@@ -538,6 +550,7 @@ onboarding:
host: localhost
port: 8080
downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+ healthCheckUri: "/onboarding-api/v1.0/healthcheck"
switchoverDetector:
gBeFqdn: AIO-BE.ecomp.idns.cip.com
@@ -597,5 +610,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/catalog-be/src/main/resources/config/error-configuration.yaml b/catalog-be/src/main/resources/config/error-configuration.yaml
index 4985ab552a..62bd7206ba 100644
--- a/catalog-be/src/main/resources/config/error-configuration.yaml
+++ b/catalog-be/src/main/resources/config/error-configuration.yaml
@@ -12,103 +12,103 @@ errors:
code: 204,
message: "No Content"
}
-#--------POL4050-----------------------------
+#--------POL4050-----------------------------
NOT_ALLOWED: {
code: 405,
message: "Error: Method not allowed.",
messageId: "POL4050"
}
-#--------POL5000-----------------------------
+#--------POL5000-----------------------------
GENERAL_ERROR: {
code: 500,
message: "Error: Internal Server Error. Please try again later.",
messageId: "POL5000"
}
-#---------POL5001------------------------------
+#---------POL5001------------------------------
MISSING_X_ECOMP_INSTANCE_ID: {
code: 400 ,
message: "Error: Missing 'X-ECOMP-InstanceID' HTTP header.",
messageId: "POL5001"
}
-#---------POL5002------------------------------
+#---------POL5002------------------------------
AUTH_REQUIRED: {
code: 401 ,
message: "Error: Authentication is required to use the API.",
messageId: "POL5002"
}
-#---------POL5003------------------------------
+#---------POL5003------------------------------
AUTH_FAILED: {
code: 403 ,
message: "Error: Not authorized to use the API.",
messageId: "POL5003"
}
-#---------POL5004------------------------------
+#---------POL5004------------------------------
MISSING_USER_ID: {
code: 400 ,
message: "Error: Missing 'USER_ID' HTTP header.",
messageId: "POL5004"
}
-#---------SVC4000-----------------------------
+#---------SVC4000-----------------------------
INVALID_CONTENT: {
code: 400,
message: "Error: Invalid content.",
messageId: "SVC4000"
}
-#---------SVC4002-----------------------------
+#---------SVC4002-----------------------------
MISSING_INFORMATION: {
code: 403,
message: "Error: Missing information.",
messageId: "SVC4002"
}
-#---------SVC4003------------------------------
-# %1 - Users's ID
+#---------SVC4003------------------------------
+# %1 - Users's ID
USER_NOT_FOUND: {
code: 404,
message: "Error: User '%1' was not found.",
messageId: "SVC4003"
}
-#---------SVC4004-----------------------------
-# %1 - Users's email address
+#---------SVC4004-----------------------------
+# %1 - Users's email address
INVALID_EMAIL_ADDRESS: {
code: 400,
message: "Error: Invalid email address '%1'.",
messageId: "SVC4004"
}
-#---------SVC4005------------------------------
+#---------SVC4005------------------------------
# %1 - role
INVALID_ROLE: {
code: 400,
message: "Error: Invalid role '%1'.",
messageId: "SVC4005"
}
-#---------SVC4006------------------------------
-# %1 - Users's USER_ID
+#---------SVC4006------------------------------
+# %1 - Users's USER_ID
USER_ALREADY_EXIST: {
code: 409,
message: "Error: User with '%1' ID already exists.",
messageId: "SVC4006"
}
-#---------SVC4007------------------------------
+#---------SVC4007------------------------------
DELETE_USER_ADMIN_CONFLICT: {
code: 409,
message: "Error: An administrator can only be deleted by another administrator.",
messageId: "SVC4007"
}
-#---------SVC4008-----------------------------
-# %1 - Users's userId
+#---------SVC4008-----------------------------
+# %1 - Users's userId
INVALID_USER_ID: {
code: 400,
message: "Error: Invalid userId '%1'.",
messageId: "SVC4008"
}
-#---------SVC4049------------------------------
+#---------SVC4049------------------------------
# %1 - service/resource
COMPONENT_MISSING_CONTACT: {
code: 400,
message: "Error: Invalid Content. Missing %1 contact.",
messageId: "SVC4049"
- }
-#---------SVC4050-----------------------------
+ }
+#---------SVC4050-----------------------------
# %1 - Service/Resource/Additional parameter
# %2 - service/resource/label name
COMPONENT_NAME_ALREADY_EXIST: {
@@ -116,90 +116,90 @@ errors:
message: "Error: %1 with name '%2' already exists.",
messageId: "SVC4050"
}
-#---------SVC4051------------------------------
-# %1 - resource/service
+#---------SVC4051------------------------------
+# %1 - resource/service
COMPONENT_MISSING_CATEGORY: {
code: 400,
message: "Error: Invalid Content. Missing %1 category.",
messageId: "SVC4051"
}
-#---------SVC4052------------------------------
+#---------SVC4052------------------------------
COMPONENT_MISSING_TAGS: {
code: 400,
message: "Error: Invalid Content. At least one tag has to be specified.",
messageId: "SVC4052"
}
-#---------SVC4053------------------------------
+#---------SVC4053------------------------------
# %1 - service/resource
COMPONENT_MISSING_DESCRIPTION: {
code: 400,
message: "Error: Invalid Content. Missing %1 description.",
messageId: "SVC4053"
}
-#---------SVC4054------------------------------
+#---------SVC4054------------------------------
# %1 - resource/service
COMPONENT_INVALID_CATEGORY: {
code: 400,
message: "Error: Invalid Content. Invalid %1 category.",
messageId: "SVC4054"
}
-#---------SVC4055------------------------------
+#---------SVC4055------------------------------
MISSING_VENDOR_NAME: {
code: 400,
message: "Error: Invalid Content. Missing vendor name.",
messageId: "SVC4055"
}
-#---------SVC4056------------------------------
+#---------SVC4056------------------------------
MISSING_VENDOR_RELEASE: {
code: 400,
message: "Error: Invalid Content. Missing vendor release.",
messageId: "SVC4056"
}
-#---------SVC4057------------------------------
+#---------SVC4057------------------------------
MISSING_DERIVED_FROM_TEMPLATE: {
code: 400,
message: "Error: Invalid Content. Missing derived from template specification.",
messageId: "SVC4057"
}
-#---------SVC4058------------------------------
+#---------SVC4058------------------------------
# %1 - service/resource
COMPONENT_MISSING_ICON: {
code: 400,
message: "Error: Invalid Content. Missing %1 icon.",
messageId: "SVC4058"
}
-#---------SVC4059------------------------------
+#---------SVC4059------------------------------
# %1 - service/resource
COMPONENT_INVALID_ICON: {
code: 400,
message: "Error: Invalid Content. Invalid %1 icon.",
messageId: "SVC4059"
}
-#---------SVC4060------------------------------
+#---------SVC4060------------------------------
PARENT_RESOURCE_NOT_FOUND: {
code: 400,
message: "Error: Invalid Content. Derived from resource template was not found.",
messageId: "SVC4060"
}
-#---------SVC4061------------------------------
+#---------SVC4061------------------------------
MULTIPLE_PARENT_RESOURCE_FOUND: {
code: 400,
message: "Error: Invalid Content. Multiple derived from resource template is not allowed.",
messageId: "SVC4061"
}
-#---------SVC4062------------------------------
+#---------SVC4062------------------------------
# %1 - service/resource
MISSING_COMPONENT_NAME: {
code: 400,
message: "Error: Invalid Content. Missing %1 name.",
messageId: "SVC4062"
}
-#---------SVC4063------------------------------
+#---------SVC4063------------------------------
#%1  -  resource/service name
RESOURCE_NOT_FOUND: {
code: 404,
@@ -207,51 +207,51 @@ errors:
messageId: "SVC4063"
}
-#---------SVC4064------------------------------
+#---------SVC4064------------------------------
# %1 - Service/Resource/Property
COMPONENT_INVALID_DESCRIPTION: {
code: 400,
message: "Error: Invalid Content. %1 description contains non-english characters.",
messageId: "SVC4064"
}
-#---------SVC4065------------------------------
+#---------SVC4065------------------------------
# %1 - Service/Resource/Property
-# %2 - max resource/service name length
+# %2 - max resource/service name length
COMPONENT_DESCRIPTION_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. %1 description exceeds limit of %2 characters.",
messageId: "SVC4065"
}
-#---------SVC4066------------------------------
-# %1 - max length
+#---------SVC4066------------------------------
+# %1 - max length
COMPONENT_TAGS_EXCEED_LIMIT: {
code: 400,
message: "Error: Invalid Content. Tags overall length exceeds limit of %1 characters.",
messageId: "SVC4066"
}
#---------SVC4067------------------------------
-# %1 - max length
+# %1 - max length
VENDOR_NAME_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Vendor name exceeds limit of %1 characters.",
messageId: "SVC4067"
}
#---------SVC4068------------------------------
-# %1 - max length
+# %1 - max length
VENDOR_RELEASE_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Vendor release exceeds limit of %1 characters.",
messageId: "SVC4068"
}
-#---------SVC4069------------------------------
+#---------SVC4069------------------------------
# %1 - Service/Resource/Product
COMPONENT_INVALID_CONTACT: {
code: 400,
message: "Error: Invalid Content. %1 Contact Id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
messageId: "SVC4069"
}
-#---------SVC4070------------------------------
+#---------SVC4070------------------------------
# %1 - Service/Resource
INVALID_COMPONENT_NAME: {
code: 400,
@@ -259,27 +259,27 @@ errors:
messageId: "SVC4070"
}
-#---------SVC4071------------------------------
+#---------SVC4071------------------------------
INVALID_VENDOR_NAME: {
code: 400,
message: 'Error: Invalid Content. Vendor name is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
messageId: "SVC4071"
}
-#---------SVC4072------------------------------
+#---------SVC4072------------------------------
INVALID_VENDOR_RELEASE: {
code: 400,
message: 'Error: Invalid Content. Vendor release is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
messageId: "SVC4072"
}
-#---------SVC4073------------------------------
+#---------SVC4073------------------------------
# %1 - Service/Resource
-# %2 - max resource/service name
+# %2 - max resource/service name
COMPONENT_NAME_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. %1 name exceeds limit of %2 characters.",
messageId: "SVC4073"
}
-#---------SVC4080------------------------------
+#---------SVC4080------------------------------
# %1 - resource/service name
# %2 - resource/service
# %3 - First name of last modifier
@@ -290,7 +290,7 @@ errors:
message: "Error: Requested '%1' %2 is locked for modification by %3 %4(%5).",
messageId: "SVC4080"
}
-#---------SVC4081-----------------------------
+#---------SVC4081-----------------------------
# %1 - resource/service name
# %2 - resource/service
# %3 - First name of last modifier
@@ -302,7 +302,7 @@ errors:
messageId: "SVC4081"
}
-#-----------SVC4082---------------------------
+#-----------SVC4082---------------------------
# %1 - resource/service name
# %2 - resource/service
# %3 - First name of last modifier
@@ -392,7 +392,7 @@ errors:
}
#-----------SVC4102---------------------------
-# %1 - capability type name
+# %1 - capability type name
CAPABILITY_TYPE_ALREADY_EXIST: {
code: 409,
message: "Error: Capability Type with name '%1' already exists.",
@@ -405,7 +405,7 @@ errors:
messageId: "SVC4114"
}
#-----------SVC4115---------------------------
-# %1 - capability type name
+# %1 - capability type name
MISSING_CAPABILITY_TYPE: {
code: 400,
message: "Error: Invalid Content. Missing Capability Type '%1'.",
@@ -483,7 +483,7 @@ errors:
message: "Error: Artifact '%1' already exists.",
messageId: "SVC4125"
}
-#---------SVC4126------------------------------
+#---------SVC4126------------------------------
# %1 - resource/service/product/...
# %2 - field (tag, vendor name...)
INVALID_FIELD_FORMAT: {
@@ -518,7 +518,7 @@ errors:
#-----------SVC4131---------------------------
# %1-resource/service
# %2-srtifact/artifacts
-# %3-semicolomn separated list of artifact
+# %3-semicolomn separated list of artifact
COMPONENT_MISSING_MANDATORY_ARTIFACTS: {
code: 403,
message: "Error: Missing mandatory informational %1 %2: [%3].",
@@ -545,60 +545,60 @@ errors:
message: "Error: Invalid Content. Missing interface life-cycle type.",
messageId: "SVC4134"
}
-#---------SVC4135------------------------------
+#---------SVC4135------------------------------
SERVICE_CATEGORY_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Service category cannot be changed once the service is certified.",
messageId: "SVC4135"
}
-#---------SVC4136------------------------------
-# %1 - distribution environment name
+#---------SVC4136------------------------------
+# %1 - distribution environment name
DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE: {
code: 500,
message: "Error: Requested distribution environment '%1' is not available.",
messageId: "SVC4136"
}
-#---------SVC4137------------------------------
-# %1 - distribution environment name
+#---------SVC4137------------------------------
+# %1 - distribution environment name
DISTRIBUTION_ENVIRONMENT_NOT_FOUND: {
code: 400,
message: "Error: Requested distribution environment '%1' was not found.",
messageId: "SVC4137"
}
-#---------SVC4138------------------------------
+#---------SVC4138------------------------------
DISTRIBUTION_ENVIRONMENT_INVALID: {
code: 400,
message: "Error: Invalid distribution environment.",
messageId: "SVC4138"
}
-#---------SVC4139------------------------------
+#---------SVC4139------------------------------
# %1 - service name
DISTRIBUTION_ARTIFACT_NOT_FOUND: {
code: 409,
message: "Error: Service '%1' cannot be distributed due to missing deployment artifacts.",
messageId: "SVC4139"
}
-#---------SVC4200------------------------------
+#---------SVC4200------------------------------
# %1 - Service/Resource
-# %2 - max icon name length
+# %2 - max icon name length
COMPONENT_ICON_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. %1 icon name exceeds limit of %2 characters.",
messageId: "SVC4200"
}
-#---------SVC4300------------------------------
+#---------SVC4300------------------------------
RESTRICTED_ACCESS: {
code: 403,
message: "Error: Restricted access.",
messageId: "SVC4300"
}
-#---------SVC4301------------------------------
+#---------SVC4301------------------------------
RESTRICTED_OPERATION: {
code: 409,
message: "Error: Restricted operation.",
messageId: "SVC4301"
}
-#---------SVC4500------------------------------
+#---------SVC4500------------------------------
MISSING_BODY: {
code: 400 ,
message: "Error: Missing request body.",
@@ -610,7 +610,7 @@ errors:
message: "Error: Invalid Content. Missing mandatory parameter 'apiPublicKey'." ,
messageId: "SVC4501"
}
-#---------SVC4502------------------------------
+#---------SVC4502------------------------------
DISTRIBUTION_ENV_DOES_NOT_EXIST: {
code: 400 ,
message: "Error: Invalid Body : Missing mandatory parameter 'distrEnvName'." ,
@@ -624,7 +624,7 @@ errors:
messageId: "SVC4503"
}
-#---------SVC4504------------------------------
+#---------SVC4504------------------------------
# %1 - Service/Resource
# %2 - service/resource version
COMPONENT_VERSION_NOT_FOUND: {
@@ -634,103 +634,103 @@ errors:
}
#-----------SVC4505---------------------------
#%1-artifact name
-
+
ARTIFACT_NOT_FOUND: {
code: 404,
message: "Error: Artifact '%1' was not found.",
messageId: "SVC4505"
}
-#---------SVC4506------------------------------
+#---------SVC4506------------------------------
MISSING_ENV_NAME: {
code: 400 ,
message: "Error: Invalid Content. Missing mandatory parameter 'distrEnvName'.",
messageId: "SVC4506"
}
-#---------SVC4507------------------------------
+#---------SVC4507------------------------------
COMPONENT_INVALID_TAGS_NO_COMP_NAME: {
code: 400,
message: "Error: Invalid Content. One of the tags should be the component name.",
messageId: "SVC4507"
}
-
-#---------SVC4508------------------------------
+
+#---------SVC4508------------------------------
SERVICE_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Service name cannot be changed once the service is certified.",
messageId: "SVC4508"
}
-#---------SVC4509------------------------------
+#---------SVC4509------------------------------
SERVICE_ICON_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Icon cannot be changed once the service is certified.",
messageId: "SVC4509"
}
-#---------SVC4510------------------------------
+#---------SVC4510------------------------------
# %1 - icon name max length
SERVICE_ICON_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Icon name exceeds limit of %1 characters.",
messageId: "SVC4510"
}
-#---------SVC4511------------------------------
+#---------SVC4511------------------------------
DISTRIBUTION_REQUESTED_NOT_FOUND: {
code: 404,
message: "Error: Requested distribution was not found.",
messageId: "SVC4511"
}
-#---------SVC4512------------------------------
+#---------SVC4512------------------------------
# %1 - Distribution ID
DISTRIBUTION_REQUESTED_FAILED: {
code: 403,
message: "Error: Requested distribution '%1' failed.",
messageId: "SVC4512"
}
-#---------SVC4513------------------------------
+#---------SVC4513------------------------------
RESOURCE_CATEGORY_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Resource category cannot be changed once the resource is certified.",
messageId: "SVC4513"
}
-#---------SVC4514------------------------------
+#---------SVC4514------------------------------
RESOURCE_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Resource name cannot be changed once the resource is certified.",
messageId: "SVC4514"
}
-#---------SVC4515------------------------------
+#---------SVC4515------------------------------
RESOURCE_ICON_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Icon cannot be changed once the resource is certified.",
messageId: "SVC4515"
}
-#---------SVC4516------------------------------
+#---------SVC4516------------------------------
RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Vendor name cannot be changed once the resource is certified.",
messageId: "SVC4516"
}
-#---------SVC4517------------------------------
+#---------SVC4517------------------------------
RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Derived from resource template cannot be changed once the resource is certified.",
messageId: "SVC4517"
}
-#---------SVC4518------------------------------
-# %1 - max length
+#---------SVC4518------------------------------
+# %1 - max length
COMPONENT_SINGLE_TAG_EXCEED_LIMIT: {
code: 400,
message: "Error: Invalid Content. Single tag exceeds limit of %1 characters.",
messageId: "SVC4518"
}
-#---------SVC4519------------------------------
+#---------SVC4519------------------------------
INVALID_DEFAULT_VALUE: {
code: 400,
message: "Error: mismatch in data-type occurred for property %1. data type is %2 and default value found is %3.",
messageId: "SVC4519"
}
-#---------SVC4520------------------------------
-# %1 - service or resource
+#---------SVC4520------------------------------
+# %1 - service or resource
ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED: {
code: 409,
message: "Error: Maximal number of additional %1 parameters was reached.",
@@ -742,7 +742,7 @@ errors:
message: "Error: Invalid Content. The Additional information label and value cannot be empty.",
messageId: "SVC4521"
}
-#---------SVC4522------------------------------
+#---------SVC4522------------------------------
# %1 - label/value
# %2 - Maximal length of %1
ADDITIONAL_INFORMATION_EXCEEDS_LIMIT: {
@@ -762,32 +762,32 @@ errors:
message: "Error: Requested additional information was not found.",
messageId: "SVC4524"
}
-#---------SVC4525------------------------------
+#---------SVC4525------------------------------
ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS: {
code: 400,
message: 'Error: Invalid Content. Additional information contains non-english characters.',
messageId: "SVC4525"
}
-#---------SVC4526------------------------------
+#---------SVC4526------------------------------
RESOURCE_INSTANCE_NOT_FOUND: {
code: 404,
message: "Error: Requested '%1' resource instance was not found.",
messageId: "SVC4526"
}
-#---------SVC4527------------------------------
+#---------SVC4527------------------------------
ASDC_VERSION_NOT_FOUND: {
code: 500,
message: 'Error: ASDC version cannot be displayed.',
messageId: "SVC4527"
}
-#---------SVC4528------------------------------
+#---------SVC4528------------------------------
# %1-artifact url/artifact label/artifact description/VNF Service Indicator
MISSING_DATA: {
code: 400,
message: "Error: Invalid content. Missing %1.",
messageId: "SVC4528"
}
-#---------SVC4529------------------------------
+#---------SVC4529------------------------------
# %1-artifact url/artifact label/artifact description/artifact name
# %2 - Maximal length of %1
EXCEEDS_LIMIT: {
@@ -795,51 +795,51 @@ errors:
message: "Error: Invalid Content. %1 exceeds limit of %2 characters.",
messageId: "SVC4529"
}
-#---------SVC4530------------------------------
+#---------SVC4530------------------------------
ARTIFACT_INVALID_TIMEOUT: {
code: 400,
message: "Error: Invalid Content. Artifact Timeout should be set to valid positive non-zero number of minutes.",
messageId: "SVC4530"
}
-#---------SVC4531------------------------------
+#---------SVC4531------------------------------
SERVICE_IS_VNF_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: VNF Indicator cannot be updated for certified service.",
messageId: "SVC4531"
}
- #---------SVC4532------------------------------
+ #---------SVC4532------------------------------
RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE: {
code: 404,
message: "Error: Requested '%1' resource instance was not found on the service '%2.",
messageId: "SVC4532"
}
- #---------SVC4533------------------------------
- # %1 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"/"YANG_XML"
+ #---------SVC4533------------------------------
+ # %1 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"/"YANG_XML"
WRONG_ARTIFACT_FILE_EXTENSION: {
code: 400,
message: "Error: Invalid file extension for %1 artifact type.",
messageId: "SVC4533"
}
-#---------SVC4534------------------------------
-# %1 - "HEAT"/"HEAT_ENV"
+#---------SVC4534------------------------------
+# %1 - "HEAT"/"HEAT_ENV"
INVALID_YAML: {
code: 400,
message: "Error: Uploaded YAML file for %1 artifact is invalid.",
messageId: "SVC4534"
}
-#---------SVC4535------------------------------
-# %1 - "HEAT"
+#---------SVC4535------------------------------
+# %1 - "HEAT"
INVALID_DEPLOYMENT_ARTIFACT_HEAT: {
code: 400,
message: "Error: Invalid %1 artifact.",
messageId: "SVC4535"
}
-#---------SVC4536------------------------------
+#---------SVC4536------------------------------
# %1 - "Resource"/"Service"
-# %2 - resource/service name
-# %3 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"
+# %2 - resource/service name
+# %3 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"
# %4 - "HEAT"/"HEAT_ENV"/"MURANO_PKG
DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS: {
code: 400,
@@ -847,80 +847,80 @@ errors:
messageId: "SVC4536"
}
-#---------SVC4537------------------------------
+#---------SVC4537------------------------------
MISSING_HEAT: {
code: 400,
message: "Error: Missing HEAT artifact. HEAT_ENV artifact cannot be uploaded without corresponding HEAT template.",
messageId: "SVC4537"
}
-#---------SVC4538------------------------------
+#---------SVC4538------------------------------
MISMATCH_HEAT_VS_HEAT_ENV: {
code: 400,
message: "Error: Invalid artifact content. Parameter's set in HEAT_ENV '%1' artifact doesn't match the parameters in HEAT '%2' artifact.",
messageId: "SVC4538"
}
-#---------SVC4539------------------------------
+#---------SVC4539------------------------------
INVALID_RESOURCE_PAYLOAD: {
code: 400,
message: "Error: Invalid resource payload.",
messageId: "SVC4539"
}
-#---------SVC4540------------------------------
+#---------SVC4540------------------------------
INVALID_TOSCA_FILE_EXTENSION: {
code: 400,
message: "Error: Invalid file extension for TOSCA template.",
messageId: "SVC4540"
}
-#---------SVC4541------------------------------
+#---------SVC4541------------------------------
INVALID_YAML_FILE: {
code: 400,
message: "Error: Invalid YAML file.",
messageId: "SVC4541"
}
-#---------SVC4542------------------------------
+#---------SVC4542------------------------------
INVALID_TOSCA_TEMPLATE: {
code: 400,
message: "Error: Invalid TOSCA template.",
messageId: "SVC4542"
}
-#---------SVC4543------------------------------
+#---------SVC4543------------------------------
NOT_RESOURCE_TOSCA_TEMPLATE: {
code: 400,
message: "Error: Imported Service TOSCA template.",
messageId: "SVC4543"
}
-#---------SVC4544------------------------------
+#---------SVC4544------------------------------
NOT_SINGLE_RESOURCE: {
code: 400,
message: "Error: Imported TOSCA template should contain one resource definition.",
messageId: "SVC4544"
}
-#---------SVC4545------------------------------
+#---------SVC4545------------------------------
INVALID_RESOURCE_NAMESPACE: {
code: 400,
message: "Error: Invalid resource namespace.",
messageId: "SVC4545"
}
-#---------SVC4546------------------------------
+#---------SVC4546------------------------------
RESOURCE_ALREADY_EXISTS: {
code: 400,
message: "Error: Imported resource already exists in ASDC Catalog.",
messageId: "SVC4546"
}
-#---------SVC4549------------------------------
+#---------SVC4549------------------------------
INVALID_RESOURCE_CHECKSUM: {
code: 400,
message: "Error: Invalid resource checksum.",
messageId: "SVC4549"
}
-#---------SVC4550------------------------------
+#---------SVC4550------------------------------
#%1  -  Consumer salt
INVALID_LENGTH: {
code: 400,
message: "Error: Invalid %1 length.",
messageId: "SVC4550"
}
- #---------SVC4551------------------------------
+ #---------SVC4551------------------------------
#%1  -  ECOMP User name
ECOMP_USER_NOT_FOUND: {
code: 404,
@@ -934,13 +934,13 @@ errors:
messageId: "SVC4552"
}
#---------SVC4553-----------------------------
- #%1  -  Consumer name / Consumer password/ Consumer salt
+ #%1  -  Consumer name / Consumer password/ Consumer salt
INVALID_CONTENT_PARAM: {
code: 400,
message: "Error: %1 is invalid.",
messageId: "SVC4553"
}
- #---------SVC4554------------------------------
+ #---------SVC4554------------------------------
# %1 - "Resource"/"Service"
COMPONENT_ARTIFACT_NOT_FOUND: {
code: 404,
@@ -954,7 +954,7 @@ errors:
message: "Error: Requested '%1' service is not ready for certification. Service has to have at least one deployment artifact.",
messageId: "SVC4554"
}
-#---------SVC4555------------------------------
+#---------SVC4555------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category"
COMPONENT_ELEMENT_INVALID_NAME_LENGTH: {
@@ -962,7 +962,7 @@ errors:
message: "Error: Invalid %1 %2 name length.",
messageId: "SVC4555"
}
-#---------SVC4556------------------------------
+#---------SVC4556------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category"
COMPONENT_ELEMENT_INVALID_NAME_FORMAT: {
@@ -970,7 +970,7 @@ errors:
message: "Error: Invalid %1 %2 name format.",
messageId: "SVC4556"
}
-#---------SVC4557------------------------------
+#---------SVC4557------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category name"
COMPONENT_CATEGORY_ALREADY_EXISTS: {
@@ -1001,7 +1001,7 @@ errors:
code: 403,
message: "Error: Submit for Testing is not permitted as your '%1' includes non-validated '%2' resource. Please use one of available validated resource versions.",
messageId: "SVC4560"
- }
+ }
#---------SVC4561------------------------------
# %1 - "resource"/"product"
# %2 - "category"
@@ -1029,108 +1029,108 @@ errors:
message: "Error: %1 grouping '%2' already exists under '%3' sub-category.",
messageId: "SVC4563"
}
-#---------SVC4564------------------------------
+#---------SVC4564------------------------------
# %1 - product name
PRODUCT_NOT_FOUND: {
code: 404,
message: "Error: Requested '%1' product was not found.",
messageId: "SVC4564"
}
-#---------SVC4565------------------------------
-# %1 - "HEAT"
-# %2 - parameter type ("string" , "boolean" , "number")
+#---------SVC4565------------------------------
+# %1 - "HEAT"
+# %2 - parameter type ("string" , "boolean" , "number")
# %3 - parameter name
INVALID_HEAT_PARAMETER_VALUE: {
code: 400,
message: "Error: Invalid %1 artifact. Invalid %2 value set for '%3' parameter.",
messageId: "SVC4565"
}
-#---------SVC4566------------------------------
-# %1 - "HEAT"
-# %2 - parameter type ("string" , "boolean" , "number")
+#---------SVC4566------------------------------
+# %1 - "HEAT"
+# %2 - parameter type ("string" , "boolean" , "number")
INVALID_HEAT_PARAMETER_TYPE: {
code: 400,
message: "Error: Invalid %1 artifact. Unsupported '%2' parameter type.",
messageId: "SVC4566"
}
-#---------SVC4567------------------------------
-# %1 - "YANG_XML"
+#---------SVC4567------------------------------
+# %1 - "YANG_XML"
INVALID_XML: {
code: 400,
message: "Error: Uploaded XML file for %1 artifact is invalid.",
messageId: "SVC4567"
}
-#---------SVC4567------------------------------
-# %1 - "User Name and UserId"
+#---------SVC4567------------------------------
+# %1 - "User Name and UserId"
# %2 -"checked-out"/"in-certification"
CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
message: "Error: User cannot be deleted. User '%1' has %2 projects.",
messageId: "SVC4567"
}
-#---------SVC4568------------------------------
-# %1 - "User Name and UserId"
+#---------SVC4568------------------------------
+# %1 - "User Name and UserId"
# %2 -"checked-out"/"in-certification"
CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
message: "Error: Role cannot be changed. User '%1' has %2 projects.",
messageId: "SVC4568"
}
-#---------SVC4570------------------------------
+#---------SVC4570------------------------------
UPDATE_USER_ADMIN_CONFLICT: {
code: 409,
message: "Error: An administrator is not allowed to change his/her role.",
messageId: "SVC4570"
}
-#---------SVC4571------------------------------
+#---------SVC4571------------------------------
SERVICE_CANNOT_CONTAIN_SUBCATEGORY: {
code: 400,
message: "Error: Sub category cannot be defined for service",
messageId: "SVC4571"
}
-#---------SVC4572------------------------------
+#---------SVC4572------------------------------
# %1 - "Resource"/"Service"
COMPONENT_TOO_MUCH_CATEGORIES: {
code: 400,
message: "Error: %1 must have only 1 category",
messageId: "SVC4572"
}
-#---------SVC4574------------------------------
+#---------SVC4574------------------------------
RESOURCE_TOO_MUCH_SUBCATEGORIES: {
code: 400,
message: "Error: Resource must have only 1 sub category",
messageId: "SVC4574"
}
-#---------SVC4575------------------------------
+#---------SVC4575------------------------------
COMPONENT_MISSING_SUBCATEGORY: {
code: 400,
message: "Error: Missing sub category",
messageId: "SVC4575"
}
- #---------SVC4576------------------------------
+ #---------SVC4576------------------------------
# %1 - "component type"
UNSUPPORTED_ERROR: {
code: 400,
message: "Error : Requested component type %1 is unsupported.",
messageId: "SVC4576"
}
- #---------SVC4577------------------------------
+ #---------SVC4577------------------------------
# %1 - "resource type"
RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES: {
code: 409,
message: "Error : Resource of type %1 cannot contain resource instances.",
messageId: "SVC4577"
}
-#---------SVC4578------------------------------
+#---------SVC4578------------------------------
# %1 - "Resource"/"Service"
-# %2 - resource/service name
-# %3 - "artifact name"
+# %2 - resource/service name
+# %3 - "artifact name"
DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS: {
code: 400,
message: "Error: %1 '%2' already has a deployment artifact named '%3'.",
messageId: "SVC4578"
}
-#---------SVC4579------------------------------
+#---------SVC4579------------------------------
# %1 - "Category"/"Sub-Category"/"Group"
# %2 - category/sub-category/grouping name.
INVALID_GROUP_ASSOCIATION: {
@@ -1138,27 +1138,27 @@ errors:
message: "Error: Invalid group association. %1 '%2' was not found.",
messageId: "SVC4579"
}
-#---------SVC4580------------------------------
+#---------SVC4580------------------------------
EMPTY_PRODUCT_CONTACTS_LIST: {
code: 400,
message: "Error: Invalid content. At least one Product Contact has to be specified.",
messageId: "SVC4580"
}
-#---------SVC4581------------------------------
+#---------SVC4581------------------------------
# %1 - UserId
INVALID_PRODUCT_CONTACT: {
code: 400,
message: "Error: Invalid content. User '%1' cannot be set as Product Contact.",
messageId: "SVC4581"
}
-#---------SVC4582------------------------------
+#---------SVC4582------------------------------
# %1 - Product
# %2 - "abbreviated"/"full"
MISSING_ONE_OF_COMPONENT_NAMES: {
code: 400,
message: "Error: Invalid content. Missing %1 %2 name.",
messageId: "SVC4582"
- }
+ }
#---------SVC4583------------------------------
# %1 - "Icon"
# %2 - "resource"/"service"/"product"
@@ -1168,10 +1168,10 @@ errors:
messageId: "SVC4583"
}
#---------SVC4584------------------------------
-# %1 - service/VF name
+# %1 - service/VF name
# %2 - "service" /"VF"
# %3 - resource instance origin type
-# %4 - resource instance name
+# %4 - resource instance name
# %5 - requirement/capability
# %6 - requirement/capability name
# %7 - "fulfilled" (for req)/"consumed (for cap)"
@@ -1180,57 +1180,57 @@ errors:
message: "Error: Requested '%1' %2 is not ready for certification. %3 '%4' has to have %5 '%6' %7.",
messageId: "SVC4584"
}
-#---------SVC4585------------------------------
+#---------SVC4585------------------------------
INVALID_OCCURRENCES: {
code: 400,
message: "Error: Invalid occurrences format.",
messageId: "SVC4585"
}
-#---------SVC4586------------------------------
-#---------SVC4586------------------------------
+#---------SVC4586------------------------------
+#---------SVC4586------------------------------
INVALID_SERVICE_API_URL: {
code: 400,
message: 'Error: Invalid Service API URL. Please check whether your URL has a valid domain extension and does not contain the following characters - #?&@%+;,=$<>~^`\[]{}|"*!',
messageId: "SVC4586"
}
-#---------SVC4587------------------------------
-# %1 - Data type name
+#---------SVC4587------------------------------
+# %1 - Data type name
DATA_TYPE_ALREADY_EXIST: {
code: 409,
message: 'Error: Data type %1 already exists.',
messageId: "SVC4587"
}
-#---------SVC4588------------------------------
-# %1 - Data type name
+#---------SVC4588------------------------------
+# %1 - Data type name
DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM: {
code: 400,
message: 'Error: Invalid Data type %1. Data type must have either a valid derived from declaration or at least one valid property',
messageId: "SVC4588"
}
-#---------SVC4589------------------------------
-# %1 - Data type name
+#---------SVC4589------------------------------
+# %1 - Data type name
DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY: {
code: 400,
message: "Error: Invalid Data type %1. 'properties' parameter cannot be empty if provided.",
messageId: "SVC4589"
}
-#---------SVC4590------------------------------
-# %1 - Property type name
+#---------SVC4590------------------------------
+# %1 - Property type name
# %2 - Property name
INVALID_PROPERTY_TYPE: {
code: 400,
message: "Error: Invalid Property type %1 in property %2.",
messageId: "SVC4590"
}
-#---------SVC4591------------------------------
+#---------SVC4591------------------------------
# %1 - Property inner type
-# %2 - Property name
+# %2 - Property name
INVALID_PROPERTY_INNER_TYPE: {
code: 400,
message: "Error: Invalid property inner type %1, in property %2",
messageId: "SVC4591"
}
-#---------SVC4592------------------------------
+#---------SVC4592------------------------------
# %1 - component instance name
# %2 - "resource instance"/"service instance"
COMPONENT_INSTANCE_NOT_FOUND: {
@@ -1238,11 +1238,11 @@ errors:
message: "Error: Requested '%1' %2 was not found.",
messageId: "SVC4592"
}
-#---------SVC4593------------------------------
+#---------SVC4593------------------------------
# %1 - component instance name
# %2 - "resource instance"/"service instance"
# %3 - "resource/"service"/"product"
-# %4 - container name
+# %4 - container name
COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER: {
code: 404,
message: "Error: Requested '%1' %2 was not found on the %3 '%4'.",
@@ -1259,20 +1259,20 @@ errors:
#---------SVC4595------------------------------
#%1 - requirement / capability
#%2 - requirement name
-#%3 - parent containing the requirement
+#%3 - parent containing the requirement
IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED: {
code: 400,
message: "Error: Imported TOSCA template contains %1 '%2' that is already defined by derived template %3.",
messageId: "SVC4595"
}
-#---------SVC4596------------------------------
+#---------SVC4596------------------------------
# %1 - Data type name
DATA_TYPE_DERIVED_IS_MISSING: {
code: 400,
message: "Error: Invalid Content. The ancestor data type %1 cannot be found in the system.",
messageId: "SVC4596"
}
-#---------SVC4597------------------------------
+#---------SVC4597------------------------------
# %1 - Data type name
# %2 - Property names
DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR: {
@@ -1280,14 +1280,14 @@ errors:
message: "Error: Invalid Content. The data type %1 contains properties named %2 which are already defined in one of its ancestors.",
messageId: "SVC4597"
}
-#---------SVC4598------------------------------
+#---------SVC4598------------------------------
# %1 - Data type name
DATA_TYPE_DUPLICATE_PROPERTY: {
code: 400,
message: "Error: Invalid Content. The data type %1 contains duplicate property.",
messageId: "SVC4598"
}
-#---------SVC4599------------------------------
+#---------SVC4599------------------------------
# %1 - Data type name
# %2 - Property names
DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE: {
@@ -1295,14 +1295,14 @@ errors:
message: "Error: Invalid Content. The data type %1 contains properties %2 which their type is this data type.",
messageId: "SVC4599"
}
-#---------SVC4600------------------------------
+#---------SVC4600------------------------------
# %1 - Data type name
DATA_TYPE_CANNOT_HAVE_PROPERTIES: {
code: 400,
message: "Error: Invalid Content. The data type %1 cannot have properties since it is of type scalar",
messageId: "SVC4600"
}
-#---------SVC4601------------------------------
+#---------SVC4601------------------------------
NOT_TOPOLOGY_TOSCA_TEMPLATE: {
code: 400,
message: "Error: TOSCA yaml file %1 cannot be modeled to VF as it does not contain 'topology_template.",
@@ -1317,7 +1317,7 @@ errors:
message: "Error: TOSCA yaml file '%1' contains node_template '%2' of type '%3' that does not represent existing VFC/CP/VL",
messageId: "SVC4602"
}
-#---------SVC4603------------------------------
+#---------SVC4603------------------------------
# %1 - component type
# %2 - component name
# %3 - state
@@ -1326,21 +1326,21 @@ errors:
message: "Error: Component instance of %1 can not be created because the component '%2' is in an illegal state %3.",
messageId: "SVC4603"
}
-#---------SVC4604------------------------------
+#---------SVC4604------------------------------
# %1 - csar file name
CSAR_INVALID: {
code: 400,
message: "Error: TOSCA CSAR '%1' is invalid. 'TOSCA-Metadata/Tosca.meta' file must be provided.",
messageId: "SVC4604"
}
-#---------SVC4605------------------------------
+#---------SVC4605------------------------------
# %1 - csar file name
CSAR_INVALID_FORMAT: {
code: 400,
message: "Error: TOSCA CSAR '%1' is invalid. Invalid 'TOSCA-Metadata/Tosca.meta' file format.",
messageId: "SVC4605"
}
-#---------SVC4606------------------------------
+#---------SVC4606------------------------------
# %1 - property name
# %2 - property type
# %3 - property innerType
@@ -1350,14 +1350,14 @@ errors:
message: "Error: Invalid default value of property %1. Data type is %2 with inner type %3 and default value found is %4.",
messageId: "SVC4606"
}
-#---------SVC4607------------------------------
+#---------SVC4607------------------------------
# %1 - csar file name
CSAR_NOT_FOUND: {
code: 400,
message: "Error: TOSCA CSAR '%1' is not found.",
messageId: "SVC4607"
}
-#---------SVC4608------------------------------
+#---------SVC4608------------------------------
# %1 - artifact name
# %2 - component type
# %3 - actual component type
@@ -1367,14 +1367,14 @@ errors:
messageId: "SVC4608"
}
-#---------SVC4609------------------------------
-# %1 - "INVALID_JSON"
+#---------SVC4609------------------------------
+# %1 - "INVALID_JSON"
INVALID_JSON: {
code: 400,
message: "Error: Uploaded JSON file for %1 artifact is invalid.",
messageId: "SVC4609"
}
-#---------SVC4610------------------------------
+#---------SVC4610------------------------------
# %1 - csar file name
# %2 - missing file name
YAML_NOT_FOUND_IN_CSAR: {
@@ -1382,21 +1382,21 @@ errors:
message: "Error - TOSCA CSAR %1 is invalid. TOSCA-Metadata/Tosca.meta refers to file %2 that is not provided.",
messageId: "SVC4610"
}
-#---------SVC4611------------------------------
+#---------SVC4611------------------------------
# %1 - group name
GROUP_MEMBER_EMPTY: {
code: 400,
message: "Error: Invalid Content. Group %1 member list was provided but does not have values",
messageId: "SVC4611"
}
-#---------SVC4612------------------------------
-# %1 - group name
+#---------SVC4612------------------------------
+# %1 - group name
GROUP_TYPE_ALREADY_EXIST: {
code: 409,
message: 'Error: Group type %1 already exists.',
messageId: "SVC4612"
}
-#---------SVC4613------------------------------
+#---------SVC4613------------------------------
# %1 - group name
# %2 - VF name(component name)
# %3 - actual component type [VF]
@@ -1404,15 +1404,15 @@ errors:
code: 409,
message: "Error: Group with name '%1' already exists in %2 %3.",
messageId: "SVC4613"
- }
-#---------SVC4614------------------------------
+ }
+#---------SVC4614------------------------------
# %1 - group type
GROUP_TYPE_IS_INVALID: {
code: 400,
message: "Error: Invalid content. Group type %1 does not exist",
messageId: "SVC4614"
}
-#---------SVC4615------------------------------
+#---------SVC4615------------------------------
# %1 - group name
GROUP_MISSING_GROUP_TYPE: {
code: 400,
@@ -1428,7 +1428,7 @@ errors:
code: 400,
message: "Error: Member '%1' listed in group '%2' is not part of '%3' %4.",
messageId: "SVC4616"
- }
+ }
#---------SVC4617------------------------------
# %1 - member name
# %2 - group name
@@ -1438,7 +1438,7 @@ errors:
message: "Error: member %1 listed in group %2 is not part of allowed members of group type %3.",
messageId: "SVC4617"
}
-#---------SVC4618------------------------------
+#---------SVC4618------------------------------
# %1 - missing file name
# %2 - csar file name
ARTIFACT_NOT_FOUND_IN_CSAR: {
@@ -1446,7 +1446,7 @@ errors:
message: "Error: artifact %1 is defined in CSAR %2 manifest but is not provided",
messageId: "SVC4618"
}
-#---------SVC4619------------------------------
+#---------SVC4619------------------------------
# %1 - artifact name
# %2 - artifact type
# %3 - existing artifact type
@@ -1455,23 +1455,23 @@ errors:
message: "Error: artifact %1 in type %2 already exists in type %3.",
messageId: "SVC4619"
}
-#---------SVC4620------------------------------
+#---------SVC4620------------------------------
FAILED_RETRIVE_ARTIFACTS_TYPES: {
code: 400,
message: "Error: Failed to retrieve list of suported artifact types.",
messageId: "SVC4620"
}
-#---------SVC4621------------------------------
+#---------SVC4621------------------------------
# %1 - artifact name
-# %2 - master
+# %2 - master
ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR: {
code: 400,
message: "Error: artifact %1 already exists in master %2 .",
messageId: "SVC4621"
}
-#---------SVC4622------------------------------
+#---------SVC4622------------------------------
# %1 - artifact name
-# %2 - artifact type
+# %2 - artifact type
# %3 - master name
# %4 - master type
ARTIFACT_NOT_VALID_IN_MASTER: {
@@ -1479,9 +1479,9 @@ errors:
message: "Error: artifact %1 in type %2 can not be exists under master %3 in type %4.",
messageId: "SVC4622"
}
-#---------SVC4623------------------------------
+#---------SVC4623------------------------------
# %1 - artifact name
-# %2 - artifact type
+# %2 - artifact type
# %3 - env name
# %4 - existing env
ARTIFACT_NOT_VALID_ENV: {
@@ -1489,7 +1489,7 @@ errors:
message: "Error: Artifact %1 in type %2 with env %3 already exists with another env %4",
messageId: "SVC4623"
}
-#---------SVC4624------------------------------
+#---------SVC4624------------------------------
# %1 - groups names
# %2 - VF name
# %3 - component type [VF ]
@@ -1498,14 +1498,14 @@ errors:
message: "Error: Invalid Content. The groups '%1' cannot be found under %2 %3.",
messageId: "SVC4624"
}
-#---------SVC4625------------------------------
+#---------SVC4625------------------------------
# %1 - groups name
GROUP_ARTIFACT_ALREADY_ASSOCIATED: {
code: 400,
message: "Error: Invalid Content. Artifact already associated to group '%1'.",
messageId: "SVC4625"
}
-#---------SVC4626------------------------------
+#---------SVC4626------------------------------
# %1 - groups name
GROUP_ARTIFACT_ALREADY_DISSOCIATED: {
code: 400,
@@ -1521,7 +1521,7 @@ errors:
message: "Error: property %1 listed in group %2 is not exist in group type %3.",
messageId: "SVC4627"
}
-#---------SVC4628------------------------------
+#---------SVC4628------------------------------
# %1 - csarUUID
# %2 - VF name
VSP_ALREADY_EXISTS: {
@@ -1529,14 +1529,14 @@ errors:
message: "Error: The VSP with UUID %1 was already imported for VF %2. Please select another or update the existing VF.",
messageId: "SVC4628"
}
-#---------SVC4629------------------------------
+#---------SVC4629------------------------------
# %1 - VF name
MISSING_CSAR_UUID: {
code: 400,
message: "Error: The Csar UUID or payload name is missing for VF %1.",
messageId: "SVC4629"
}
-#---------SVC4630------------------------------
+#---------SVC4630------------------------------
# %1 - VF name
# %2 - new csarUUID
# %3 - old csarUUID
@@ -1545,8 +1545,8 @@ errors:
message: "Error: Resource %1 cannot be updated using CsarUUID %2 since the resource is linked to a different VSP with csarUUID %3.",
messageId: "SVC4630"
}
-#---------SVC4631------------------------------
-# %1 - policy name
+#---------SVC4631------------------------------
+# %1 - policy name
POLICY_TYPE_ALREADY_EXIST: {
code: 409,
message: "Error: Policy type %1 already exists.",
@@ -1593,7 +1593,7 @@ errors:
code: 404,
message: "Error: Requested '%1' attribute was not found.",
messageId: "SVC4637"
- }
+ }
#-----------SVC4638---------------------------
#%1 - attribute name
ATTRIBUTE_ALREADY_EXIST: {
@@ -1661,7 +1661,7 @@ errors:
message: "Error: Invalid Content. VF Module name '%1' contains invalid characters",
messageId: "SVC4646"
}
-
+
#---------SVC4647------------------------------
# %1 - "modifiedName"
INVALID_VF_MODULE_NAME_MODIFICATION: {
@@ -1699,23 +1699,23 @@ errors:
message: "Error: Once resource is certified, derived_from can be changed only to a sibling",
messageId: "SVC4651"
}
-#---------SVC4652------------------------------
+#---------SVC4652------------------------------
# %1 - resource/service
COMPONENT_INVALID_SUBCATEGORY: {
code: 400,
message: "Error: Invalid Content. Invalid %1 sub category.",
messageId: "SVC4652"
}
-#---------SVC4653------------------------------
-# %1 - group instance uniqueId
+#---------SVC4653------------------------------
+# %1 - group instance uniqueId
# %2 - service uniqueId
GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE: {
code: 404,
message: "Error: Requested group instance %1 was not found on component %2.",
messageId: "SVC4653"
}
-#---------SVC4654------------------------------
-# %1 - group property name
+#---------SVC4654------------------------------
+# %1 - group property name
# %2 - valid min limit value
# %3 - valid max limit value
INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE: {
@@ -1723,8 +1723,8 @@ errors:
message: "Error: Value of %1 must be not higher than %2, and not lower than %3.",
messageId: "SVC4654"
}
-#---------SVC4655------------------------------
-# %1 - group property name
+#---------SVC4655------------------------------
+# %1 - group property name
# %2 - valid min limit value
# %3 - valid max limit value
INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE: {
@@ -1732,15 +1732,15 @@ errors:
message: "Error: Value of %1 must be between %2 and %3.",
messageId: "SVC4655"
}
-#---------SVC4656------------------------------
-# %1 - group property name
+#---------SVC4656------------------------------
+# %1 - group property name
# %2 - lower/higher
# %3 - valid max/min value
INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER: {
code: 400,
message: "Error: Value of %1 must be %2 or equals to %3.",
messageId: "SVC4656"
- }
+ }
#---------SVC4657------------------------------
# %1 - certificationRequest / startTesting
RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID: {
@@ -1752,7 +1752,7 @@ errors:
# %1 – asset type [service / resource ]
# %2 – main asset uuid
# %3 – not found asset type [service / resource]
-# %4 – not found asset name
+# %4 – not found asset name
ASSET_NOT_FOUND_DURING_CSAR_CREATION: {
code: 400,
message: "Error: CSAR packaging failed for %1 %2. %3 %4 was not found",
@@ -1761,7 +1761,7 @@ errors:
#---------SVC4659------------------------------
# %1 – asset type [service / resource ]
# %2 – main asset uuid
-# %3 – Artifact name
+# %3 – Artifact name
# %4 – Artifact uuid
ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION: {
code: 400,
@@ -1777,18 +1777,78 @@ errors:
messageId: "SVC4660"
}
#---------SVC4661------------------------------
-# %1 - version
-# %2 - conformance level
+# %1 - assetType
+# %2 - matching generic node type name
TOSCA_SCHEMA_FILES_NOT_FOUND: {
code: 400,
message: "Error: CSAR packaging failed. TOSCA schema files for SDC-Version: %1 and Conformance-Level %2 were not found",
messageId: "SVC4661"
}
-#---------SVC4662------------------------------
+#---------SVC4662------------------------------
# %1 - file name
# %2 - parser error
TOSCA_PARSE_ERROR: {
code: 400,
message: "Error: Invalid TOSCA template in file %1. %2",
messageId: "SVC4662"
+ }
+#---------SVC4663------------------------------
+# %1 - max length
+ RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Resource vendor model number exceeds limit of %1 characters.",
+ messageId: "SVC4663"
+ }
+#---------SVC4664------------------------------
+ INVALID_RESOURCE_VENDOR_MODEL_NUMBER: {
+ code: 400,
+ message: 'Error: Invalid Content. Resource vendor model number is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4664"
+ }
+#---------SVC4665------------------------------
+# %1 - max length
+ SERVICE_TYPE_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Service type exceeds limit of %1 characters.",
+ messageId: "SVC4665"
+ }
+#---------SVC4666------------------------------
+ INVALID_SERVICE_TYPE: {
+ code: 400,
+ message: 'Error: Invalid Content. Serivce type is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4666"
+ }
+#---------SVC4667------------------------------
+# %1 - max length
+ SERVICE_ROLE_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Service role exceeds limit of %1 characters.",
+ messageId: "SVC4667"
+ }
+#---------SVC4668------------------------------
+ INVALID_SERVICE_ROLE: {
+ code: 400,
+ message: 'Error: Invalid Content. Service role is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4668"
+ }
+
+#---------SVC4669-----------------------------
+ INVALID_RESOURCE_TYPE: {
+ code: 400,
+ message: "Error: Invalid resource type.",
+ messageId: "SVC4669"
+ }
+#---------SVC4670------------------------------
+ ARTIFACT_NAME_INVALID: {
+ code: 400,
+ message: "Error: Artifact name is invalid.",
+ messageId: "SVC4670"
+ }
+#---------SVC4671------------------------------
+# %1 - VSP name
+# %2 - VFC name
+ CFVC_LOOP_DETECTED: {
+ code: 400,
+ message: 'Error: VSP %1 cannot be imported. The VSP contains internal loop in VFC %2',
+ messageId: "SVC4671"
} \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml
index 63d70c699e..da15414d9d 100644
--- a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml
+++ b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.yml
@@ -1196,4 +1196,57 @@ org.openecomp.datatypes.Naming:
type: string
required: false
+# NFoD
+org.openecomp.datatypes.flavors.ComputeFlavor:
+ derived_from: tosca.datatypes.Root
+ properties:
+ num_cpus:
+ type: integer
+ disk_size:
+ type: scalar-unit.size
+ mem_size:
+ type: scalar-unit.size
+
+org.openecomp.datatypes.flavors.LicenseFlavor:
+ derived_from: tosca.datatypes.Root
+ properties:
+ feature_group_uuid:
+ type: string
+
+org.openecomp.datatypes.flavors.VendorInfo:
+ derived_from: tosca.datatypes.Root
+ properties:
+ manufacturer_reference_number:
+ type: string
+ vendor_model:
+ type: string
+
+org.openecomp.datatypes.flavors.DeploymentFlavor:
+ derived_from: tosca.datatypes.Root
+ properties:
+ sp_part_number:
+ type: string
+ vendor_info:
+ type: org.openecomp.datatypes.flavors.VendorInfo
+ compute_flavor:
+ type: org.openecomp.datatypes.flavors.ComputeFlavor
+ license_flavor:
+ type: org.openecomp.datatypes.flavors.LicenseFlavor
+ required: false
+
+
+org.openecomp.datatypes.ImageInfo:
+ derived_from: tosca.datatypes.Root
+ properties:
+ software_version:
+ type: string
+ file_name:
+ type: string
+ file_hash:
+ type: string
+ description: checksum/signature
+ file_hash_type:
+ type: string
+ required: false
+ default: md5
diff --git a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip
index 9c5964df1d..08d4bfc3a5 100644
--- a/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip
+++ b/catalog-be/src/main/resources/import/tosca/data-types/dataTypes.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types.zip b/catalog-be/src/main/resources/import/tosca/heat-types.zip
deleted file mode 100644
index ebb5afd09d..0000000000
--- a/catalog-be/src/main/resources/import/tosca/heat-types.zip
+++ /dev/null
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_PNF/Generic_PNF.json b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_PNF/Generic_PNF.json
new file mode 100644
index 0000000000..cfa11dc3c7
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_PNF/Generic_PNF.json
@@ -0,0 +1,21 @@
+{
+ "payloadName": "Generic_PNF.yml",
+ "contactId": "jh0003",
+ "name": "Generic_PNF",
+ "description": "Represents a generic PNF.",
+ "resourceIconPath": "defaulticon",
+ "resourceType": "ABSTRACT",
+ "categories": [
+ {
+ "name": "Generic",
+ "subcategories": [
+ {
+ "name": "Abstract"
+ }
+ ]
+ }
+],
+ "tags": [
+ "Generic_PNF"
+ ]
+} \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_PNF/Generic_PNF.yml b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_PNF/Generic_PNF.yml
new file mode 100644
index 0000000000..db3fc7cd3e
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_PNF/Generic_PNF.yml
@@ -0,0 +1,11 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.abstract.nodes.PNF:
+ derived_from: tosca.nodes.Root
+ properties:
+ nf_function:
+ type: string
+ nf_role:
+ type: string
+ nf_type:
+ type: string \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/Generic_PNF/Generic_PNF.zip b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_PNF/Generic_PNF.zip
new file mode 100644
index 0000000000..fc5d706514
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/Generic_PNF/Generic_PNF.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.yml b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.yml
index e73cafe100..9160a9ba22 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.yml
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.yml
@@ -37,16 +37,16 @@ node_types:
subnetpoolid:
type: string
requirements:
- virtualLink:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- virtualBinding:
- capability: tosca.capabilities.network.Bindable
- relationship: tosca.relationships.network.BindsTo
- external_virtualLink:
- capability: tosca.capabilities.network.Linkable
- relationship: tosca.relationships.network.LinksTo
- node: org.openecomp.resource.vl.VL
+ - virtualLink:
+ capability: tosca.capabilities.network.Linkable
+ relationship: tosca.relationships.network.LinksTo
+ - virtualBinding:
+ capability: tosca.capabilities.network.Bindable
+ relationship: tosca.relationships.network.BindsTo
+ - external_virtualLink:
+ capability: tosca.capabilities.network.Linkable
+ relationship: tosca.relationships.network.LinksTo
+ node: org.openecomp.resource.vl.VL
capabilities:
internal_connectionPoint:
type: tosca.capabilities.Node
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.zip b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.zip
index a26c323819..5e18a2474a 100644
--- a/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.zip
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/extCp/extCp.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/multiFlavorVFC/multiFlavorVFC.json b/catalog-be/src/main/resources/import/tosca/heat-types/multiFlavorVFC/multiFlavorVFC.json
new file mode 100644
index 0000000000..1d27562aae
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/multiFlavorVFC/multiFlavorVFC.json
@@ -0,0 +1,21 @@
+{
+ "payloadName": "multiFlavorVFC.yml",
+ "contactId": "jh0003",
+ "name": "multiFlavorVFC",
+ "description": "Represents a generic multi flavor VFC.",
+ "resourceIconPath": "defaulticon",
+ "resourceType": "VFC",
+ "categories": [
+ {
+ "name": "Generic",
+ "subcategories": [
+ {
+ "name": "Abstract"
+ }
+ ]
+ }
+],
+ "tags": [
+ "multiFlavorVFC"
+ ]
+} \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/multiFlavorVFC/multiFlavorVFC.yml b/catalog-be/src/main/resources/import/tosca/heat-types/multiFlavorVFC/multiFlavorVFC.yml
new file mode 100644
index 0000000000..2df111d1c5
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/multiFlavorVFC/multiFlavorVFC.yml
@@ -0,0 +1,10 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.abstract.nodes.MultiFlavorVFC:
+ derived_from: org.openecomp.resource.abstract.nodes.VFC
+ properties:
+ images:
+ type: map
+ entry_schema:
+ type: org.openecomp.datatypes.ImageInfo
+ required: false
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/multiFlavorVFC/multiFlavorVFC.zip b/catalog-be/src/main/resources/import/tosca/heat-types/multiFlavorVFC/multiFlavorVFC.zip
new file mode 100644
index 0000000000..d73488d0c0
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/multiFlavorVFC/multiFlavorVFC.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/vnfConfiguration/vnfConfiguration.json b/catalog-be/src/main/resources/import/tosca/heat-types/vnfConfiguration/vnfConfiguration.json
new file mode 100644
index 0000000000..2a955ab955
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/vnfConfiguration/vnfConfiguration.json
@@ -0,0 +1,21 @@
+{
+ "payloadName": "vnfConfiguration.yml",
+ "contactId": "jh0003",
+ "name": "vnfConfiguration",
+ "description": "Configuration parameters for VNF",
+ "resourceIconPath": "vnfconfiguration",
+ "resourceType": "VFC",
+ "categories": [
+ {
+ "name": "Generic",
+ "subcategories": [
+ {
+ "name": "Abstract"
+ }
+ ]
+ }
+],
+ "tags": [
+ "vnfConfiguration"
+ ]
+} \ No newline at end of file
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/vnfConfiguration/vnfConfiguration.yml b/catalog-be/src/main/resources/import/tosca/heat-types/vnfConfiguration/vnfConfiguration.yml
new file mode 100644
index 0000000000..4ee624615a
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/vnfConfiguration/vnfConfiguration.yml
@@ -0,0 +1,10 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+node_types:
+ org.openecomp.resource.abstract.nodes.VnfConfiguration:
+ derived_from: tosca.nodes.Root
+ properties:
+ allowed_flavors:
+ description: a collection of all flavor valuesets available for a given VFC
+ type: map
+ entry_schema:
+ type: org.openecomp.datatypes.flavors.DeploymentFlavor
diff --git a/catalog-be/src/main/resources/import/tosca/heat-types/vnfConfiguration/vnfConfiguration.zip b/catalog-be/src/main/resources/import/tosca/heat-types/vnfConfiguration/vnfConfiguration.zip
new file mode 100644
index 0000000000..03a7d535f2
--- /dev/null
+++ b/catalog-be/src/main/resources/import/tosca/heat-types/vnfConfiguration/vnfConfiguration.zip
Binary files differ
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py b/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py
index f65aefacf1..e7eaa8610b 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/importHeatTypes.py
@@ -37,7 +37,8 @@ def importHeatTypes(beHost, bePort, adminUser, fileDir, updateversion):
"eline",
"abstractSubstitute",
"Generic_VFC",
- "Generic_VF",
+ "Generic_VF",
+ "Generic_PNF",
"Generic_Service",
"contrailNetworkRules",
"contrailPort",
@@ -48,7 +49,9 @@ def importHeatTypes(beHost, bePort, adminUser, fileDir, updateversion):
"contrailCompute",
"contrailV2VirtualMachineInterface",
"subInterface",
- "contrailV2VLANSubInterface"
+ "contrailV2VLANSubInterface",
+ "multiFlavorVFC",
+ "vnfConfiguration"
]
responseCodes = [200, 201]
diff --git a/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py b/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py
index 7c0746fb55..7315ec0635 100644
--- a/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py
+++ b/catalog-be/src/main/resources/scripts/import/tosca/upgradeHeatTypes1707.py
@@ -26,7 +26,8 @@ def upgradeHeatTypes1707(beHost, bePort, adminUser, fileDir, updateversion):
"extVl",
"extCp",
"Generic_VFC",
- "Generic_VF",
+ "Generic_VF",
+ "Generic_PNF",
"Generic_Service",
"globalPort",
"globalNetwork",
@@ -37,6 +38,8 @@ def upgradeHeatTypes1707(beHost, bePort, adminUser, fileDir, updateversion):
"contrailVirtualNetwork",
"neutronNet",
"neutronPort",
+ "multiFlavorVFC",
+ "vnfConfiguration"
]
responseCodes = [200, 201]
diff --git a/catalog-be/src/main/webapp/WEB-INF/web.xml b/catalog-be/src/main/webapp/WEB-INF/web.xml
index 9b7a55a4dd..889b1fac60 100644
--- a/catalog-be/src/main/webapp/WEB-INF/web.xml
+++ b/catalog-be/src/main/webapp/WEB-INF/web.xml
@@ -77,7 +77,6 @@
<servlet-mapping>
<servlet-name>jerseyDistribution</servlet-name>
<url-pattern>/sdc/*</url-pattern>
- <url-pattern>/asdc/*</url-pattern>
</servlet-mapping>
<servlet>
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java
index 6af338ebcf..68d47590f0 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/HealthCheckBusinessLogicTest.java
@@ -23,19 +23,30 @@ package org.openecomp.sdc.be.components;
import java.util.ArrayList;
import java.util.List;
+import javax.annotation.Resource;
+
import org.junit.Test;
import org.openecomp.sdc.be.components.impl.HealthCheckBusinessLogic;
+import org.openecomp.sdc.be.dao.cassandra.schema.SdcSchemaUtils;
+import org.openecomp.sdc.be.dao.titan.TitanGenericDao;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
+import org.openecomp.sdc.be.resources.data.UserData;
import org.openecomp.sdc.common.api.HealthCheckInfo;
import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckComponent;
import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus;
+import com.datastax.driver.core.Cluster;
+
+import fj.data.Either;
+
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class HealthCheckBusinessLogicTest {
HealthCheckBusinessLogic healthCheckBusinessLogic = new HealthCheckBusinessLogic();
-
+
@Test
public void checkStausUpdated() {
@@ -51,18 +62,13 @@ public class HealthCheckBusinessLogicTest {
HealthCheckInfo checkInfoTitanUp = new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.UP, null, null);
HealthCheckInfo checkInfoTitanDown = new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.DOWN, null, null);
- HealthCheckInfo checkInfoEsUp = new HealthCheckInfo(HealthCheckComponent.ES, HealthCheckStatus.UP, null, null);
- HealthCheckInfo checkInfoEsDown = new HealthCheckInfo(HealthCheckComponent.ES, HealthCheckStatus.DOWN, null, null);
-
/*
* HealthCheckInfo checkInfoUebUp = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UP, null, null); HealthCheckInfo checkInfoUebDown = new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.DOWN, null, null);
*/
checkInfosLeft.add(checkInfoTitanUp);
- checkInfosLeft.add(checkInfoEsUp);
checkInfosRight.add(checkInfoTitanUp);
- checkInfosRight.add(checkInfoEsUp);
statusChanged = healthCheckBusinessLogic.anyStatusChanged(checkInfosLeft, checkInfosRight);
assertFalse("check false", statusChanged);
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 09f2570a35..f0b2865373 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
@@ -130,7 +130,7 @@ public class ResourceImportManagerTest {
testSetDerivedFrom(resource);
testSetProperties(resource);
- Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true));
+ Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false));
}
@Test
@@ -159,7 +159,7 @@ public class ResourceImportManagerTest {
Mockito.verify(resourceBusinessLogic, Mockito.times(0)).createOrUpdateResourceByImport(Mockito.any(Resource.class), Mockito.eq(user), Mockito.eq(true), Mockito.eq(false), Mockito.eq(true));
- Mockito.verify(resourceBusinessLogic, Mockito.times(0)).propagateStateToCertified(Mockito.eq(user), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true));
+ Mockito.verify(resourceBusinessLogic, Mockito.times(0)).propagateStateToCertified(Mockito.eq(user), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false));
}
@@ -181,7 +181,7 @@ public class ResourceImportManagerTest {
Resource resource = createResource.left().value().left;
testSetCapabilities(resource);
- Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true));
+ Mockito.verify(resourceBusinessLogic, Mockito.times(1)).propagateStateToCertified(Mockito.eq(user), Mockito.eq(resource), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false));
Mockito.verify(resourceBusinessLogic, Mockito.times(1)).createOrUpdateResourceByImport(resource, user, true, false, true);
}
@@ -215,7 +215,7 @@ public class ResourceImportManagerTest {
}
});
- when(resourceBusinessLogic.propagateStateToCertified(Mockito.any(User.class), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true)))
+ when(resourceBusinessLogic.propagateStateToCertified(Mockito.any(User.class), Mockito.any(Resource.class), Mockito.any(LifecycleChangeInfoWithAction.class), Mockito.eq(false), Mockito.eq(true), Mockito.eq(false)))
.thenAnswer(new Answer<Either<Resource, ResponseFormat>>() {
public Either<Resource, ResponseFormat> answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java
index f6d2b6bf84..bbfa8bf236 100644
--- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java
+++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java
@@ -49,9 +49,7 @@ import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
-import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
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;
@@ -67,6 +65,7 @@ import org.openecomp.sdc.be.model.PropertyDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache;
+import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation;
import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
@@ -110,6 +109,7 @@ public class ResourceBusinessLogicTest {
public static final String RESOURCE_NAME = "My-Resource_Name with space";
private static final String GENERIC_VF_NAME = "org.openecomp.resource.abstract.nodes.VF";
private static final String GENERIC_VFC_NAME = "org.openecomp.resource.abstract.nodes.VFC";
+ private static final String GENERIC_PNF_NAME = "org.openecomp.resource.abstract.nodes.PNF";
final ServletContext servletContext = Mockito.mock(ServletContext.class);
IAuditingManager iAuditingManager = null;
@@ -118,6 +118,7 @@ public class ResourceBusinessLogicTest {
UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class);
+ NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class);
TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class);
final LifecycleBusinessLogic lifecycleBl = Mockito.mock(LifecycleBusinessLogic.class);
final ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class);
@@ -135,8 +136,9 @@ public class ResourceBusinessLogicTest {
Resource resourceResponse = null;
Resource genericVF = null;
Resource genericVFC = null;
+ Resource genericPNF = null;
ComponentsUtils componentsUtils = new ComponentsUtils();
- ArtifactsBusinessLogic artifactManager = Mockito.mock(ArtifactsBusinessLogic.class);
+ ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic();
CsarOperation csarOperation = Mockito.mock(CsarOperation.class);
Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<String, DataTypeDefinition>();
@@ -187,6 +189,7 @@ public class ResourceBusinessLogicTest {
Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);
when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);
+ when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);
Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true);
when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists);
@@ -195,14 +198,7 @@ public class ResourceBusinessLogicTest {
when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists);
when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK);
when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK);
-
- ArtifactDefinition artifactDef = new ArtifactDefinition();
- artifactDef.setUniqueId("123.123");
- Either<ArtifactDefinition, StorageOperationStatus> returnEither = Either.left(artifactDef);
- when(artifactManager.createArtifactPlaceHolderInfo(Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef);
-
- when(artifactManager.addHeatEnvArtifact(Mockito.any(ArtifactDefinition.class), Mockito.any(ArtifactDefinition.class), Mockito.anyString(), Mockito.any(NodeTypeEnum.class), Mockito.anyString())).thenReturn(returnEither);
-
+
// createResource
resourceResponse = createResourceObject(true);
Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse);
@@ -213,6 +209,7 @@ public class ResourceBusinessLogicTest {
when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes));
// BL object
+ artifactManager.nodeTemplateOperation = nodeTemplateOperation;
bl = new ResourceBusinessLogic();
bl.setElementDao(mockElementDao);
bl.setUserAdmin(mockUserAdmin);
@@ -281,6 +278,7 @@ public class ResourceBusinessLogicTest {
resource.setDerivedFrom(template);
resource.setVendorName("Motorola");
resource.setVendorRelease("1.0.0");
+ resource.setResourceVendorModelNumber("");
resource.setContactId("ya5467");
resource.setIcon("MyIcon");
resource.setCsarUUID("valid_vf.csar");
@@ -364,6 +362,7 @@ public class ResourceBusinessLogicTest {
testVendorNameWrongFormatCreate();
testVendorReleaseWrongFormat();
testVendorReleaseExceedsLimitCreate();
+ testResourceVendorModelNumberExceedsLimit();
testResourceVendorNameMissing();
testResourceVendorReleaseMissing();
testResourceCategoryExist();
@@ -667,13 +666,23 @@ public class ResourceBusinessLogicTest {
private void testVendorNameExceedsLimit() {
Resource resourceExccedsVendorNameLimit = createResourceObject(false);
- String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
+ String tooLongVendorName = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
resourceExccedsVendorNameLimit.setVendorName(tooLongVendorName);
Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorNameLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
assertTrue(createResponse.isRight());
assertResponse(createResponse, ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT, "" + ValidationUtils.VENDOR_NAME_MAX_LENGTH);
}
+
+ private void testResourceVendorModelNumberExceedsLimit() {
+ Resource resourceExccedsVendorModelNumberLimit = createResourceObject(false);
+ String tooLongVendorModelNumber = "h1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9Eh1KSyJh9E";
+ resourceExccedsVendorModelNumberLimit.setResourceVendorModelNumber(tooLongVendorModelNumber);
+
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resourceExccedsVendorModelNumberLimit, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isRight());
+ assertResponse(createResponse, ActionStatus.RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, "" + ValidationUtils.RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH);
+ }
private void testVendorNameWrongFormatCreate() {
Resource resource = createResourceObject(false);
@@ -1641,7 +1650,7 @@ public class ResourceBusinessLogicTest {
@Test
- public void testGeneratedInputs() {
+ public void testVFGeneratedInputs() {
Resource resource = createVF();
List<InputDefinition> inputs = resource.getInputs();
@@ -1654,7 +1663,7 @@ public class ResourceBusinessLogicTest {
}
@Test
- public void testUpdateGenericInputsToLatestOnCheckout() {
+ public void testVFUpdateGenericInputsToLatestOnCheckout() {
//create a VF that is derived from generic version 1.0
Resource resource = createVF();
@@ -1680,7 +1689,7 @@ public class ResourceBusinessLogicTest {
@Test
- public void testUpdateGenericInputsToLatestOnCheckoutNotPerformed() {
+ public void testVFUpdateGenericInputsToLatestOnCheckoutNotPerformed() {
//create a VF that is derived from generic version 1.0
Resource resource = createVF();
@@ -1713,6 +1722,21 @@ public class ResourceBusinessLogicTest {
assertTrue(resource.getInputs().stream().filter(p -> null == p.getOwnerId()).findAny().get().getType().equals("integer"));
}
+ @Test
+ public void testPNFGeneratedInputsNoGeneratedInformationalArtifacts() {
+
+ Resource resource = createPNF();
+ List<InputDefinition> inputs = resource.getInputs();
+ assertTrue(8 == inputs.size());
+ for(InputDefinition input : inputs){
+ assertNotNull(input.getOwnerId());
+ }
+ assertTrue(resource.getDerivedFromGenericType().equals(genericPNF.getToscaResourceName()));
+ assertTrue(resource.getDerivedFromGenericVersion().equals(genericPNF.getVersion()));
+ assertTrue(0 == resource.getArtifacts().size());
+ }
+
+
private Resource createVF() {
genericVF = setupGenericTypeMock(GENERIC_VF_NAME);
@@ -1726,6 +1750,19 @@ public class ResourceBusinessLogicTest {
return createResponse.left().value();
}
+ private Resource createPNF() {
+
+ genericPNF = setupGenericTypeMock(GENERIC_PNF_NAME);
+ when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_PNF_NAME)).thenReturn(Either.left(genericPNF));
+ Resource resource = createResourceObject(true);
+ resource.setDerivedFrom(null);
+ resource.setResourceType(ResourceTypeEnum.PNF);
+ when(toscaOperationFacade.createToscaComponent(resource)).thenReturn(Either.left(resource));
+ Either<Resource, ResponseFormat> createResponse = bl.createResource(resource, AuditingActionEnum.CREATE_RESOURCE, user, null, null);
+ assertTrue(createResponse.isLeft());
+ return createResponse.left().value();
+ }
+
private Resource setupGenericTypeMock(String toscaName) {
@@ -1746,4 +1783,6 @@ public class ResourceBusinessLogicTest {
return genericType;
}
+
+
}
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 69b08bd1c1..1488f13015 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
@@ -50,6 +50,7 @@ import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.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;
@@ -168,7 +169,8 @@ public class LifecycleTestBase {
resource.setVendorRelease("1.0.0");
resource.setContactId("yavivi");
resource.setIcon("MyIcon.jpg");
-
+ resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue());
+
return resource;
}
@@ -191,6 +193,7 @@ public class LifecycleTestBase {
resource.setVendorRelease("1.0.0");
resource.setContactId("yavivi");
resource.setIcon("MyIcon.jpg");
+ resource.setToscaType(ToscaElementTypeEnum.NodeType.getValue());
return resource;
}
diff --git a/catalog-be/src/test/resources/config/catalog-be/configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/configuration.yaml
index cd5c58957d..6a94f7268a 100644
--- a/catalog-be/src/test/resources/config/catalog-be/configuration.yaml
+++ b/catalog-be/src/test/resources/config/catalog-be/configuration.yaml
@@ -5,8 +5,6 @@ identificationHeaderFields:
- HTTP_IV_REMOTE_ADDRESS
- HTTP_CSP_WSTYPE
-
-
# catalog backend hostname
beFqdn: sdccatalog.att.com
@@ -24,33 +22,71 @@ beSslPort: 8443
version: 1.0
released: 2012-11-30
-toscaConformanceLevel: 3.0
+toscaConformanceLevel: 4.0
+minToscaConformanceLevel: 3.0
titanCfgFile: /home/vagrant/catalog-be/config/catalog-be/titan.properties
titanInMemoryGraph: true
titanLockTimeout: 600
+
+# The interval to try and reconnect to titan DB when it is down during ASDC startup:
titanReconnectIntervalInSeconds: 3
+
+# The read timeout towards Titan DB when health check is invoked:
titanHealthCheckReadTimeout: 1
+
+# The interval to try and reconnect to Elasticsearch when it is down during ASDC startup:
esReconnectIntervalInSeconds: 3
uebHealthCheckReconnectIntervalInSeconds: 15
uebHealthCheckReadTimeout: 4
+
# Protocols
protocols:
- http
- https
+# Default imports
+defaultImports:
+ - nodes:
+ file: nodes.yml
+ - datatypes:
+ file: data.yml
+ - capabilities:
+ file: capabilities.yml
+ - relationships:
+ file: relationships.yml
+ - groups:
+ file: groups.yml
+ - policies:
+ file: policies.yml
+
# Users
users:
tom: passwd
bob: passwd
-
+
neo4j:
host: neo4jhost
port: 7474
user: neo4j
password: "12345"
-
+
+cassandraConfig:
+ cassandraHosts: ['localhost']
+ localDataCenter:
+ reconnectTimeout : 30000
+ authenticate: false
+ username: koko
+ password: bobo
+ ssl: false
+ truststorePath : /path/path
+ truststorePassword : 123123
+ keySpaces:
+ - { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+ - { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+ - { name: sdccomponent, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
+ - { name: sdcrepository, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
#Application-specific settings of ES
elasticSearch:
@@ -68,7 +104,7 @@ elasticSearch:
# Legal values for creationPeriod - year, month, day, hour, minute, none (meaning no time-based behaviour).
#
# If no creationPeriod is configured for indexPrefix, default behavour is creationPeriod: month.
-
+
indicesTimeFrequency:
- indexPrefix: auditingevents
creationPeriod: month
@@ -110,7 +146,8 @@ resourceTypes: &allResourceTypes
- VL
- VF
- VFCMT
-
+ - Abstract
+
# validForResourceTypes usage
# validForResourceTypes:
# - VF
@@ -128,14 +165,19 @@ deploymentResourceArtifacts:
# displayName: "Network HEAT Template"
# type: HEAT_NET
# validForResourceTypes: *allResourceTypes
-
+
deploymentResourceInstanceArtifacts:
heatEnv:
displayName: "HEAT ENV"
type: HEAT_ENV
description: "Auto-generated HEAT Environment deployment artifact"
fileExtension: "env"
-
+ VfHeatEnv:
+ displayName: "VF HEAT ENV"
+ type: HEAT_ENV
+ description: "VF Auto-generated HEAT Environment deployment artifact"
+ fileExtension: "env"
+
#tosca artifacts placeholders
toscaArtifacts:
assetToscaTemplate:
@@ -149,9 +191,12 @@ toscaArtifacts:
type: TOSCA_CSAR
description: TOSCA definition package of the asset
+
#Informational artifacts placeHolder
excludeResourceCategory:
- Generic
+excludeResourceType:
+ - PNF
informationalResourceArtifacts:
features:
displayName: Features
@@ -174,7 +219,7 @@ informationalResourceArtifacts:
resourceSecurityTemplate:
displayName: Resource Security Template
type: OTHER
-
+
excludeServiceCategory:
informationalServiceArtifacts:
@@ -217,7 +262,7 @@ informationalServiceArtifacts:
serviceSecurityTemplate:
displayName: Service Security Template
type: OTHER
-
+
serviceApiArtifacts:
configuration:
displayName: Configuration
@@ -238,7 +283,6 @@ serviceApiArtifacts:
displayName: Testing
type: OTHER
-
additionalInformationMaxNumberOfKeys: 50
systemMonitoring:
@@ -261,6 +305,7 @@ serviceDeploymentArtifacts:
MODEL_QUERY_SPEC:
acceptedTypes:
- xml
+#AAI Artifacts
AAI_SERVICE_MODEL:
acceptedTypes:
- xml
@@ -284,19 +329,19 @@ resourceDeploymentArtifacts:
- yaml
- yml
validForResourceTypes: *allResourceTypes
- HEAT_NESTED:
+ HEAT_NET:
acceptedTypes:
- yaml
- yml
validForResourceTypes: *allResourceTypes
- HEAT_ARTIFACT:
- acceptedTypes:
- validForResourceTypes: *allResourceTypes
- HEAT_NET:
+ HEAT_NESTED:
acceptedTypes:
- yaml
- yml
validForResourceTypes: *allResourceTypes
+ HEAT_ARTIFACT:
+ acceptedTypes:
+ validForResourceTypes: *allResourceTypes
YANG_XML:
acceptedTypes:
- xml
@@ -321,10 +366,55 @@ resourceDeploymentArtifacts:
acceptedTypes:
- xml
validForResourceTypes: *allResourceTypes
+ LIFECYCLE_OPERATIONS:
+ acceptedTypes:
+ - yaml
+ - yml
+ validForResourceTypes:
+ - VF
+ - VFC
+ VES_EVENTS:
+ acceptedTypes:
+ - yaml
+ - yml
+ validForResourceTypes: *allResourceTypes
+ PERFORMANCE_COUNTER:
+ acceptedTypes:
+ - csv
+ validForResourceTypes: *allResourceTypes
APPC_CONFIG:
acceptedTypes:
validForResourceTypes:
- VF
+ DCAE_TOSCA:
+ acceptedTypes:
+ - yml
+ - yaml
+ validForResourceTypes:
+ - VF
+ - VFCMT
+ DCAE_JSON:
+ acceptedTypes:
+ - json
+ validForResourceTypes:
+ - VF
+ - VFCMT
+ DCAE_POLICY:
+ acceptedTypes:
+ - emf
+ validForResourceTypes:
+ - VF
+ - VFCMT
+ DCAE_DOC:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+ - VFCMT
+ DCAE_EVENT:
+ acceptedTypes:
+ validForResourceTypes:
+ - VF
+ - VFCMT
AAI_VF_MODEL:
acceptedTypes:
- xml
@@ -344,7 +434,7 @@ resourceDeploymentArtifacts:
SNMP_TRAP:
acceptedTypes:
validForResourceTypes: *allResourceTypes
-
+
resourceInstanceDeploymentArtifacts:
HEAT_ENV:
acceptedTypes:
@@ -352,6 +442,29 @@ resourceInstanceDeploymentArtifacts:
VF_MODULES_METADATA:
acceptedTypes:
- json
+ VES_EVENTS:
+ acceptedTypes:
+ - yaml
+ - yml
+ PERFORMANCE_COUNTER:
+ acceptedTypes:
+ - csv
+ DCAE_INVENTORY_TOSCA:
+ acceptedTypes:
+ - yml
+ - yaml
+ DCAE_INVENTORY_JSON:
+ acceptedTypes:
+ - json
+ DCAE_INVENTORY_POLICY:
+ acceptedTypes:
+ - emf
+ DCAE_INVENTORY_DOC:
+ acceptedTypes:
+ DCAE_INVENTORY_BLUEPRINT:
+ acceptedTypes:
+ DCAE_INVENTORY_EVENT:
+ acceptedTypes:
SNMP_POLL:
acceptedTypes:
validForResourceTypes: *allResourceTypes
@@ -389,7 +502,14 @@ resourceInformationalArtifacts:
validForResourceTypes: *allResourceTypes
OTHER:
acceptedTypes:
- validForResourceTypes: *allResourceTypes
+ validForResourceTypes:
+ - VFC
+ - CP
+ - VL
+ - VF
+ - VFCMT
+ - Abstract
+ - PNF
SNMP_POLL:
acceptedTypes:
validForResourceTypes: *allResourceTypes
@@ -404,13 +524,10 @@ resourceInformationalArtifacts:
resourceInformationalDeployedArtifacts:
-
requirementsToFulfillBeforeCert:
- CP:
- - tosca.capabilities.network.Bindable
capabilitiesToConsumeBeforeCert:
-
+
unLoggedUrls:
- /sdc2/rest/healthCheck
@@ -422,23 +539,20 @@ cleanComponentsConfiguration:
artifactsIndex: resources
-cassandraConfig:
- cassandraHosts: ['localhost']
- localDataCenter:
- reconnectTimeout : 30000
- authenticate: false
- username: koko
- password: bobo
- ssl: false
- truststorePath : /path/path
- truststorePassword : 123123
- keySpaces:
- - { name: sdcaudit, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
- - { name: sdcartifact, replicationStrategy: SimpleStrategy, replicationInfo: ['1']}
-
+heatEnvArtifactHeader: ""
+heatEnvArtifactFooter: ""
+
+onboarding:
+ protocol: http
+ host: localhost
+ port: 8080
+ downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+ healthCheckUri: "/onboarding-api/v1.0/healthcheck"
+
+
switchoverDetector:
- gBeFqdn: AIO-BE.ecomp.idns.com
- gFeFqdn: AIO-FE.ecomp.idns.com
+ gBeFqdn: AIO-BE.ecomp.idns.cip.com
+ gFeFqdn: AIO-FE.ecomp.idns.cip.com
beVip: 0.0.0.0
feVip: 0.0.0.0
beResolveAttempts: 3
@@ -454,25 +568,15 @@ switchoverDetector:
changePriorityBody: '{"name":"AIO-BE.ecomp.idns.com","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-BE.ecomp.idns.com","no_ad_redirection":false,"v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_be","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_be"],"failover_policy":["FAILALL"]},"comment":"AIO BE G-fqdn","intended_app_proto":"DNS"}'}
feSet: { changePriorityUrl: "http://xxx.com/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.com?user=root",
changePriorityBody: '{"comment":"AIO G-fqdn","name":"AIO-FE.ecomp.idns.com","v4groups":{"failover_groups":["/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_mg_fe","/crt/CipDomain.ECOMP-ASDC-DEVST/config/groups/group_bs_fe"],"failover_policy":["FAILALL"]},"no_ad_redirection":false,"intended_app_proto":"DNS","uri":"/crt/CipDomain.ECOMP-ASDC-DEVST/config/sites/AIO-FE.ecomp.idns.com"}'}
-
-
-heatEnvArtifactHeader: ""
-heatEnvArtifactFooter: ""
-
-onboarding:
- protocol: http
- host: localhost
- port: 8080
- downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
applicationL1Cache:
datatypes:
- enabled: true
+ enabled: false
firstRunDelay: 10
pollIntervalInSec: 60
applicationL2Cache:
- enabled: false
+ enabled: true
catalogL1Cache:
enabled: true
resourcesSizeInCache: 300
@@ -482,8 +586,28 @@ applicationL2Cache:
syncIntervalInSecondes: 60
waitOnShutDownInMinutes: 30
numberOfCacheWorkers: 4
+
+toscaValidators:
+ stringMaxLength: 2500
+
+disableAudit: false
+
+vfModuleProperties:
+ min_vf_module_instances:
+ forBaseModule: 1
+ forNonBaseModule: 0
+ max_vf_module_instances:
+ forBaseModule: 1
+ forNonBaseModule:
+ initial_count:
+ forBaseModule: 1
+ forNonBaseModule: 0
+ vf_module_type:
+ forBaseModule: Base
+ forNonBaseModule: Expansion
+
genericAssetNodeTypes:
VFC: 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/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml b/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml
index e131929aa7..591a961150 100644
--- a/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml
+++ b/catalog-be/src/test/resources/config/catalog-be/error-configuration.yaml
@@ -12,103 +12,103 @@ errors:
code: 204,
message: "No Content"
}
-#--------POL4050-----------------------------
+#--------POL4050-----------------------------
NOT_ALLOWED: {
code: 405,
message: "Error: Method not allowed.",
messageId: "POL4050"
}
-#--------POL5000-----------------------------
+#--------POL5000-----------------------------
GENERAL_ERROR: {
code: 500,
message: "Error: Internal Server Error. Please try again later.",
messageId: "POL5000"
}
-#---------POL5001------------------------------
+#---------POL5001------------------------------
MISSING_X_ECOMP_INSTANCE_ID: {
code: 400 ,
message: "Error: Missing 'X-ECOMP-InstanceID' HTTP header.",
messageId: "POL5001"
}
-#---------POL5002------------------------------
+#---------POL5002------------------------------
AUTH_REQUIRED: {
code: 401 ,
message: "Error: Authentication is required to use the API.",
messageId: "POL5002"
}
-#---------POL5003------------------------------
+#---------POL5003------------------------------
AUTH_FAILED: {
code: 403 ,
message: "Error: Not authorized to use the API.",
messageId: "POL5003"
}
-#---------POL5004------------------------------
+#---------POL5004------------------------------
MISSING_USER_ID: {
code: 400 ,
message: "Error: Missing 'USER_ID' HTTP header.",
messageId: "POL5004"
}
-#---------SVC4000-----------------------------
+#---------SVC4000-----------------------------
INVALID_CONTENT: {
code: 400,
message: "Error: Invalid content.",
messageId: "SVC4000"
}
-#---------SVC4002-----------------------------
+#---------SVC4002-----------------------------
MISSING_INFORMATION: {
code: 403,
message: "Error: Missing information.",
messageId: "SVC4002"
}
-#---------SVC4003------------------------------
-# %1 - Users's ID
+#---------SVC4003------------------------------
+# %1 - Users's ID
USER_NOT_FOUND: {
code: 404,
message: "Error: User '%1' was not found.",
messageId: "SVC4003"
}
-#---------SVC4004-----------------------------
-# %1 - Users's email address
+#---------SVC4004-----------------------------
+# %1 - Users's email address
INVALID_EMAIL_ADDRESS: {
code: 400,
message: "Error: Invalid email address '%1'.",
messageId: "SVC4004"
}
-#---------SVC4005------------------------------
+#---------SVC4005------------------------------
# %1 - role
INVALID_ROLE: {
code: 400,
message: "Error: Invalid role '%1'.",
messageId: "SVC4005"
}
-#---------SVC4006------------------------------
-# %1 - Users's USER_ID
+#---------SVC4006------------------------------
+# %1 - Users's USER_ID
USER_ALREADY_EXIST: {
code: 409,
message: "Error: User with '%1' ID already exists.",
messageId: "SVC4006"
}
-#---------SVC4007------------------------------
+#---------SVC4007------------------------------
DELETE_USER_ADMIN_CONFLICT: {
code: 409,
message: "Error: An administrator can only be deleted by another administrator.",
messageId: "SVC4007"
}
-#---------SVC4008-----------------------------
-# %1 - Users's userId
+#---------SVC4008-----------------------------
+# %1 - Users's userId
INVALID_USER_ID: {
code: 400,
message: "Error: Invalid userId '%1'.",
messageId: "SVC4008"
}
-#---------SVC4049------------------------------
+#---------SVC4049------------------------------
# %1 - service/resource
COMPONENT_MISSING_CONTACT: {
code: 400,
message: "Error: Invalid Content. Missing %1 contact.",
messageId: "SVC4049"
- }
-#---------SVC4050-----------------------------
+ }
+#---------SVC4050-----------------------------
# %1 - Service/Resource/Additional parameter
# %2 - service/resource/label name
COMPONENT_NAME_ALREADY_EXIST: {
@@ -116,90 +116,90 @@ errors:
message: "Error: %1 with name '%2' already exists.",
messageId: "SVC4050"
}
-#---------SVC4051------------------------------
-# %1 - resource/service
+#---------SVC4051------------------------------
+# %1 - resource/service
COMPONENT_MISSING_CATEGORY: {
code: 400,
message: "Error: Invalid Content. Missing %1 category.",
messageId: "SVC4051"
}
-#---------SVC4052------------------------------
+#---------SVC4052------------------------------
COMPONENT_MISSING_TAGS: {
code: 400,
message: "Error: Invalid Content. At least one tag has to be specified.",
messageId: "SVC4052"
}
-#---------SVC4053------------------------------
+#---------SVC4053------------------------------
# %1 - service/resource
COMPONENT_MISSING_DESCRIPTION: {
code: 400,
message: "Error: Invalid Content. Missing %1 description.",
messageId: "SVC4053"
}
-#---------SVC4054------------------------------
+#---------SVC4054------------------------------
# %1 - resource/service
COMPONENT_INVALID_CATEGORY: {
code: 400,
message: "Error: Invalid Content. Invalid %1 category.",
messageId: "SVC4054"
}
-#---------SVC4055------------------------------
+#---------SVC4055------------------------------
MISSING_VENDOR_NAME: {
code: 400,
message: "Error: Invalid Content. Missing vendor name.",
messageId: "SVC4055"
}
-#---------SVC4056------------------------------
+#---------SVC4056------------------------------
MISSING_VENDOR_RELEASE: {
code: 400,
message: "Error: Invalid Content. Missing vendor release.",
messageId: "SVC4056"
}
-#---------SVC4057------------------------------
+#---------SVC4057------------------------------
MISSING_DERIVED_FROM_TEMPLATE: {
code: 400,
message: "Error: Invalid Content. Missing derived from template specification.",
messageId: "SVC4057"
}
-#---------SVC4058------------------------------
+#---------SVC4058------------------------------
# %1 - service/resource
COMPONENT_MISSING_ICON: {
code: 400,
message: "Error: Invalid Content. Missing %1 icon.",
messageId: "SVC4058"
}
-#---------SVC4059------------------------------
+#---------SVC4059------------------------------
# %1 - service/resource
COMPONENT_INVALID_ICON: {
code: 400,
message: "Error: Invalid Content. Invalid %1 icon.",
messageId: "SVC4059"
}
-#---------SVC4060------------------------------
+#---------SVC4060------------------------------
PARENT_RESOURCE_NOT_FOUND: {
code: 400,
message: "Error: Invalid Content. Derived from resource template was not found.",
messageId: "SVC4060"
}
-#---------SVC4061------------------------------
+#---------SVC4061------------------------------
MULTIPLE_PARENT_RESOURCE_FOUND: {
code: 400,
message: "Error: Invalid Content. Multiple derived from resource template is not allowed.",
messageId: "SVC4061"
}
-#---------SVC4062------------------------------
+#---------SVC4062------------------------------
# %1 - service/resource
MISSING_COMPONENT_NAME: {
code: 400,
message: "Error: Invalid Content. Missing %1 name.",
messageId: "SVC4062"
}
-#---------SVC4063------------------------------
+#---------SVC4063------------------------------
#%1  -  resource/service name
RESOURCE_NOT_FOUND: {
code: 404,
@@ -207,51 +207,51 @@ errors:
messageId: "SVC4063"
}
-#---------SVC4064------------------------------
+#---------SVC4064------------------------------
# %1 - Service/Resource/Property
COMPONENT_INVALID_DESCRIPTION: {
code: 400,
message: "Error: Invalid Content. %1 description contains non-english characters.",
messageId: "SVC4064"
}
-#---------SVC4065------------------------------
+#---------SVC4065------------------------------
# %1 - Service/Resource/Property
-# %2 - max resource/service name length
+# %2 - max resource/service name length
COMPONENT_DESCRIPTION_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. %1 description exceeds limit of %2 characters.",
messageId: "SVC4065"
}
-#---------SVC4066------------------------------
-# %1 - max length
+#---------SVC4066------------------------------
+# %1 - max length
COMPONENT_TAGS_EXCEED_LIMIT: {
code: 400,
message: "Error: Invalid Content. Tags overall length exceeds limit of %1 characters.",
messageId: "SVC4066"
}
#---------SVC4067------------------------------
-# %1 - max length
+# %1 - max length
VENDOR_NAME_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Vendor name exceeds limit of %1 characters.",
messageId: "SVC4067"
}
#---------SVC4068------------------------------
-# %1 - max length
+# %1 - max length
VENDOR_RELEASE_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Vendor release exceeds limit of %1 characters.",
messageId: "SVC4068"
}
-#---------SVC4069------------------------------
+#---------SVC4069------------------------------
# %1 - Service/Resource/Product
COMPONENT_INVALID_CONTACT: {
code: 400,
- message: "Error: Invalid Content. %1 Contact id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
+ message: "Error: Invalid Content. %1 Contact Id should be in format 'mnnnnnn' or 'aannna' or 'aannnn', where m=m ,a=a-zA-Z and n=0-9",
messageId: "SVC4069"
}
-#---------SVC4070------------------------------
+#---------SVC4070------------------------------
# %1 - Service/Resource
INVALID_COMPONENT_NAME: {
code: 400,
@@ -259,27 +259,27 @@ errors:
messageId: "SVC4070"
}
-#---------SVC4071------------------------------
+#---------SVC4071------------------------------
INVALID_VENDOR_NAME: {
code: 400,
message: 'Error: Invalid Content. Vendor name is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
messageId: "SVC4071"
}
-#---------SVC4072------------------------------
+#---------SVC4072------------------------------
INVALID_VENDOR_RELEASE: {
code: 400,
message: 'Error: Invalid Content. Vendor release is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
messageId: "SVC4072"
}
-#---------SVC4073------------------------------
+#---------SVC4073------------------------------
# %1 - Service/Resource
-# %2 - max resource/service name
+# %2 - max resource/service name
COMPONENT_NAME_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. %1 name exceeds limit of %2 characters.",
messageId: "SVC4073"
}
-#---------SVC4080------------------------------
+#---------SVC4080------------------------------
# %1 - resource/service name
# %2 - resource/service
# %3 - First name of last modifier
@@ -290,7 +290,7 @@ errors:
message: "Error: Requested '%1' %2 is locked for modification by %3 %4(%5).",
messageId: "SVC4080"
}
-#---------SVC4081-----------------------------
+#---------SVC4081-----------------------------
# %1 - resource/service name
# %2 - resource/service
# %3 - First name of last modifier
@@ -302,7 +302,7 @@ errors:
messageId: "SVC4081"
}
-#-----------SVC4082---------------------------
+#-----------SVC4082---------------------------
# %1 - resource/service name
# %2 - resource/service
# %3 - First name of last modifier
@@ -392,7 +392,7 @@ errors:
}
#-----------SVC4102---------------------------
-# %1 - capability type name
+# %1 - capability type name
CAPABILITY_TYPE_ALREADY_EXIST: {
code: 409,
message: "Error: Capability Type with name '%1' already exists.",
@@ -405,7 +405,7 @@ errors:
messageId: "SVC4114"
}
#-----------SVC4115---------------------------
-# %1 - capability type name
+# %1 - capability type name
MISSING_CAPABILITY_TYPE: {
code: 400,
message: "Error: Invalid Content. Missing Capability Type '%1'.",
@@ -483,7 +483,7 @@ errors:
message: "Error: Artifact '%1' already exists.",
messageId: "SVC4125"
}
-#---------SVC4126------------------------------
+#---------SVC4126------------------------------
# %1 - resource/service/product/...
# %2 - field (tag, vendor name...)
INVALID_FIELD_FORMAT: {
@@ -518,7 +518,7 @@ errors:
#-----------SVC4131---------------------------
# %1-resource/service
# %2-srtifact/artifacts
-# %3-semicolomn separated list of artifact
+# %3-semicolomn separated list of artifact
COMPONENT_MISSING_MANDATORY_ARTIFACTS: {
code: 403,
message: "Error: Missing mandatory informational %1 %2: [%3].",
@@ -545,60 +545,60 @@ errors:
message: "Error: Invalid Content. Missing interface life-cycle type.",
messageId: "SVC4134"
}
-#---------SVC4135------------------------------
+#---------SVC4135------------------------------
SERVICE_CATEGORY_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Service category cannot be changed once the service is certified.",
messageId: "SVC4135"
}
-#---------SVC4136------------------------------
-# %1 - distribution environment name
+#---------SVC4136------------------------------
+# %1 - distribution environment name
DISTRIBUTION_ENVIRONMENT_NOT_AVAILABLE: {
code: 500,
message: "Error: Requested distribution environment '%1' is not available.",
messageId: "SVC4136"
}
-#---------SVC4137------------------------------
-# %1 - distribution environment name
+#---------SVC4137------------------------------
+# %1 - distribution environment name
DISTRIBUTION_ENVIRONMENT_NOT_FOUND: {
code: 400,
message: "Error: Requested distribution environment '%1' was not found.",
messageId: "SVC4137"
}
-#---------SVC4138------------------------------
+#---------SVC4138------------------------------
DISTRIBUTION_ENVIRONMENT_INVALID: {
code: 400,
message: "Error: Invalid distribution environment.",
messageId: "SVC4138"
}
-#---------SVC4139------------------------------
+#---------SVC4139------------------------------
# %1 - service name
DISTRIBUTION_ARTIFACT_NOT_FOUND: {
code: 409,
message: "Error: Service '%1' cannot be distributed due to missing deployment artifacts.",
messageId: "SVC4139"
}
-#---------SVC4200------------------------------
+#---------SVC4200------------------------------
# %1 - Service/Resource
-# %2 - max icon name length
+# %2 - max icon name length
COMPONENT_ICON_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. %1 icon name exceeds limit of %2 characters.",
messageId: "SVC4200"
}
-#---------SVC4300------------------------------
+#---------SVC4300------------------------------
RESTRICTED_ACCESS: {
code: 403,
message: "Error: Restricted access.",
messageId: "SVC4300"
}
-#---------SVC4301------------------------------
+#---------SVC4301------------------------------
RESTRICTED_OPERATION: {
code: 409,
message: "Error: Restricted operation.",
messageId: "SVC4301"
}
-#---------SVC4500------------------------------
+#---------SVC4500------------------------------
MISSING_BODY: {
code: 400 ,
message: "Error: Missing request body.",
@@ -610,7 +610,7 @@ errors:
message: "Error: Invalid Content. Missing mandatory parameter 'apiPublicKey'." ,
messageId: "SVC4501"
}
-#---------SVC4502------------------------------
+#---------SVC4502------------------------------
DISTRIBUTION_ENV_DOES_NOT_EXIST: {
code: 400 ,
message: "Error: Invalid Body : Missing mandatory parameter 'distrEnvName'." ,
@@ -624,7 +624,7 @@ errors:
messageId: "SVC4503"
}
-#---------SVC4504------------------------------
+#---------SVC4504------------------------------
# %1 - Service/Resource
# %2 - service/resource version
COMPONENT_VERSION_NOT_FOUND: {
@@ -634,103 +634,103 @@ errors:
}
#-----------SVC4505---------------------------
#%1-artifact name
-
+
ARTIFACT_NOT_FOUND: {
code: 404,
message: "Error: Artifact '%1' was not found.",
messageId: "SVC4505"
}
-#---------SVC4506------------------------------
+#---------SVC4506------------------------------
MISSING_ENV_NAME: {
code: 400 ,
message: "Error: Invalid Content. Missing mandatory parameter 'distrEnvName'.",
messageId: "SVC4506"
}
-#---------SVC4507------------------------------
+#---------SVC4507------------------------------
COMPONENT_INVALID_TAGS_NO_COMP_NAME: {
code: 400,
message: "Error: Invalid Content. One of the tags should be the component name.",
messageId: "SVC4507"
}
-
-#---------SVC4508------------------------------
+
+#---------SVC4508------------------------------
SERVICE_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Service name cannot be changed once the service is certified.",
messageId: "SVC4508"
}
-#---------SVC4509------------------------------
+#---------SVC4509------------------------------
SERVICE_ICON_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Icon cannot be changed once the service is certified.",
messageId: "SVC4509"
}
-#---------SVC4510------------------------------
+#---------SVC4510------------------------------
# %1 - icon name max length
SERVICE_ICON_EXCEEDS_LIMIT: {
code: 400,
message: "Error: Invalid Content. Icon name exceeds limit of %1 characters.",
messageId: "SVC4510"
}
-#---------SVC4511------------------------------
+#---------SVC4511------------------------------
DISTRIBUTION_REQUESTED_NOT_FOUND: {
code: 404,
message: "Error: Requested distribution was not found.",
messageId: "SVC4511"
}
-#---------SVC4512------------------------------
+#---------SVC4512------------------------------
# %1 - Distribution ID
DISTRIBUTION_REQUESTED_FAILED: {
code: 403,
message: "Error: Requested distribution '%1' failed.",
messageId: "SVC4512"
}
-#---------SVC4513------------------------------
+#---------SVC4513------------------------------
RESOURCE_CATEGORY_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Resource category cannot be changed once the resource is certified.",
messageId: "SVC4513"
}
-#---------SVC4514------------------------------
+#---------SVC4514------------------------------
RESOURCE_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Resource name cannot be changed once the resource is certified.",
messageId: "SVC4514"
}
-#---------SVC4515------------------------------
+#---------SVC4515------------------------------
RESOURCE_ICON_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Icon cannot be changed once the resource is certified.",
messageId: "SVC4515"
}
-#---------SVC4516------------------------------
+#---------SVC4516------------------------------
RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Vendor name cannot be changed once the resource is certified.",
messageId: "SVC4516"
}
-#---------SVC4517------------------------------
+#---------SVC4517------------------------------
RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: Derived from resource template cannot be changed once the resource is certified.",
messageId: "SVC4517"
}
-#---------SVC4518------------------------------
-# %1 - max length
+#---------SVC4518------------------------------
+# %1 - max length
COMPONENT_SINGLE_TAG_EXCEED_LIMIT: {
code: 400,
message: "Error: Invalid Content. Single tag exceeds limit of %1 characters.",
messageId: "SVC4518"
}
-#---------SVC4519------------------------------
+#---------SVC4519------------------------------
INVALID_DEFAULT_VALUE: {
code: 400,
message: "Error: mismatch in data-type occurred for property %1. data type is %2 and default value found is %3.",
messageId: "SVC4519"
}
-#---------SVC4520------------------------------
-# %1 - service or resource
+#---------SVC4520------------------------------
+# %1 - service or resource
ADDITIONAL_INFORMATION_MAX_NUMBER_REACHED: {
code: 409,
message: "Error: Maximal number of additional %1 parameters was reached.",
@@ -742,7 +742,7 @@ errors:
message: "Error: Invalid Content. The Additional information label and value cannot be empty.",
messageId: "SVC4521"
}
-#---------SVC4522------------------------------
+#---------SVC4522------------------------------
# %1 - label/value
# %2 - Maximal length of %1
ADDITIONAL_INFORMATION_EXCEEDS_LIMIT: {
@@ -762,32 +762,32 @@ errors:
message: "Error: Requested additional information was not found.",
messageId: "SVC4524"
}
-#---------SVC4525------------------------------
+#---------SVC4525------------------------------
ADDITIONAL_INFORMATION_VALUE_NOT_ALLOWED_CHARACTERS: {
code: 400,
message: 'Error: Invalid Content. Additional information contains non-english characters.',
messageId: "SVC4525"
}
-#---------SVC4526------------------------------
+#---------SVC4526------------------------------
RESOURCE_INSTANCE_NOT_FOUND: {
code: 404,
message: "Error: Requested '%1' resource instance was not found.",
messageId: "SVC4526"
}
-#---------SVC4527------------------------------
+#---------SVC4527------------------------------
ASDC_VERSION_NOT_FOUND: {
code: 500,
message: 'Error: ASDC version cannot be displayed.',
messageId: "SVC4527"
}
-#---------SVC4528------------------------------
+#---------SVC4528------------------------------
# %1-artifact url/artifact label/artifact description/VNF Service Indicator
MISSING_DATA: {
code: 400,
message: "Error: Invalid content. Missing %1.",
messageId: "SVC4528"
}
-#---------SVC4529------------------------------
+#---------SVC4529------------------------------
# %1-artifact url/artifact label/artifact description/artifact name
# %2 - Maximal length of %1
EXCEEDS_LIMIT: {
@@ -795,51 +795,51 @@ errors:
message: "Error: Invalid Content. %1 exceeds limit of %2 characters.",
messageId: "SVC4529"
}
-#---------SVC4530------------------------------
+#---------SVC4530------------------------------
ARTIFACT_INVALID_TIMEOUT: {
code: 400,
message: "Error: Invalid Content. Artifact Timeout should be set to valid positive non-zero number of minutes.",
messageId: "SVC4530"
}
-#---------SVC4531------------------------------
+#---------SVC4531------------------------------
SERVICE_IS_VNF_CANNOT_BE_CHANGED: {
code: 400,
message: "Error: VNF Indicator cannot be updated for certified service.",
messageId: "SVC4531"
}
- #---------SVC4532------------------------------
+ #---------SVC4532------------------------------
RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE: {
code: 404,
message: "Error: Requested '%1' resource instance was not found on the service '%2.",
messageId: "SVC4532"
}
- #---------SVC4533------------------------------
- # %1 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"/"YANG_XML"
+ #---------SVC4533------------------------------
+ # %1 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"/"YANG_XML"
WRONG_ARTIFACT_FILE_EXTENSION: {
code: 400,
message: "Error: Invalid file extension for %1 artifact type.",
messageId: "SVC4533"
}
-#---------SVC4534------------------------------
-# %1 - "HEAT"/"HEAT_ENV"
+#---------SVC4534------------------------------
+# %1 - "HEAT"/"HEAT_ENV"
INVALID_YAML: {
code: 400,
message: "Error: Uploaded YAML file for %1 artifact is invalid.",
messageId: "SVC4534"
}
-#---------SVC4535------------------------------
-# %1 - "HEAT"
+#---------SVC4535------------------------------
+# %1 - "HEAT"
INVALID_DEPLOYMENT_ARTIFACT_HEAT: {
code: 400,
message: "Error: Invalid %1 artifact.",
messageId: "SVC4535"
}
-#---------SVC4536------------------------------
+#---------SVC4536------------------------------
# %1 - "Resource"/"Service"
-# %2 - resource/service name
-# %3 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"
+# %2 - resource/service name
+# %3 - "HEAT"/"HEAT_ENV"/"MURANO_PKG"
# %4 - "HEAT"/"HEAT_ENV"/"MURANO_PKG
DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS: {
code: 400,
@@ -847,80 +847,80 @@ errors:
messageId: "SVC4536"
}
-#---------SVC4537------------------------------
+#---------SVC4537------------------------------
MISSING_HEAT: {
code: 400,
message: "Error: Missing HEAT artifact. HEAT_ENV artifact cannot be uploaded without corresponding HEAT template.",
messageId: "SVC4537"
}
-#---------SVC4538------------------------------
+#---------SVC4538------------------------------
MISMATCH_HEAT_VS_HEAT_ENV: {
code: 400,
message: "Error: Invalid artifact content. Parameter's set in HEAT_ENV '%1' artifact doesn't match the parameters in HEAT '%2' artifact.",
messageId: "SVC4538"
}
-#---------SVC4539------------------------------
+#---------SVC4539------------------------------
INVALID_RESOURCE_PAYLOAD: {
code: 400,
message: "Error: Invalid resource payload.",
messageId: "SVC4539"
}
-#---------SVC4540------------------------------
+#---------SVC4540------------------------------
INVALID_TOSCA_FILE_EXTENSION: {
code: 400,
message: "Error: Invalid file extension for TOSCA template.",
messageId: "SVC4540"
}
-#---------SVC4541------------------------------
+#---------SVC4541------------------------------
INVALID_YAML_FILE: {
code: 400,
message: "Error: Invalid YAML file.",
messageId: "SVC4541"
}
-#---------SVC4542------------------------------
+#---------SVC4542------------------------------
INVALID_TOSCA_TEMPLATE: {
code: 400,
message: "Error: Invalid TOSCA template.",
messageId: "SVC4542"
}
-#---------SVC4543------------------------------
+#---------SVC4543------------------------------
NOT_RESOURCE_TOSCA_TEMPLATE: {
code: 400,
message: "Error: Imported Service TOSCA template.",
messageId: "SVC4543"
}
-#---------SVC4544------------------------------
+#---------SVC4544------------------------------
NOT_SINGLE_RESOURCE: {
code: 400,
message: "Error: Imported TOSCA template should contain one resource definition.",
messageId: "SVC4544"
}
-#---------SVC4545------------------------------
+#---------SVC4545------------------------------
INVALID_RESOURCE_NAMESPACE: {
code: 400,
message: "Error: Invalid resource namespace.",
messageId: "SVC4545"
}
-#---------SVC4546------------------------------
+#---------SVC4546------------------------------
RESOURCE_ALREADY_EXISTS: {
code: 400,
message: "Error: Imported resource already exists in ASDC Catalog.",
messageId: "SVC4546"
}
-#---------SVC4549------------------------------
+#---------SVC4549------------------------------
INVALID_RESOURCE_CHECKSUM: {
code: 400,
message: "Error: Invalid resource checksum.",
messageId: "SVC4549"
}
-#---------SVC4550------------------------------
+#---------SVC4550------------------------------
#%1  -  Consumer salt
INVALID_LENGTH: {
code: 400,
message: "Error: Invalid %1 length.",
messageId: "SVC4550"
}
- #---------SVC4551------------------------------
+ #---------SVC4551------------------------------
#%1  -  ECOMP User name
ECOMP_USER_NOT_FOUND: {
code: 404,
@@ -934,13 +934,13 @@ errors:
messageId: "SVC4552"
}
#---------SVC4553-----------------------------
- #%1  -  Consumer name / Consumer password/ Consumer salt
+ #%1  -  Consumer name / Consumer password/ Consumer salt
INVALID_CONTENT_PARAM: {
code: 400,
message: "Error: %1 is invalid.",
messageId: "SVC4553"
}
- #---------SVC4554------------------------------
+ #---------SVC4554------------------------------
# %1 - "Resource"/"Service"
COMPONENT_ARTIFACT_NOT_FOUND: {
code: 404,
@@ -954,7 +954,7 @@ errors:
message: "Error: Requested '%1' service is not ready for certification. Service has to have at least one deployment artifact.",
messageId: "SVC4554"
}
-#---------SVC4555------------------------------
+#---------SVC4555------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category"
COMPONENT_ELEMENT_INVALID_NAME_LENGTH: {
@@ -962,7 +962,7 @@ errors:
message: "Error: Invalid %1 %2 name length.",
messageId: "SVC4555"
}
-#---------SVC4556------------------------------
+#---------SVC4556------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category"
COMPONENT_ELEMENT_INVALID_NAME_FORMAT: {
@@ -970,7 +970,7 @@ errors:
message: "Error: Invalid %1 %2 name format.",
messageId: "SVC4556"
}
-#---------SVC4557------------------------------
+#---------SVC4557------------------------------
#%1 - "Resource"/"Service"/"Product"
#%2 - "category name"
COMPONENT_CATEGORY_ALREADY_EXISTS: {
@@ -1001,7 +1001,7 @@ errors:
code: 403,
message: "Error: Submit for Testing is not permitted as your '%1' includes non-validated '%2' resource. Please use one of available validated resource versions.",
messageId: "SVC4560"
- }
+ }
#---------SVC4561------------------------------
# %1 - "resource"/"product"
# %2 - "category"
@@ -1029,108 +1029,108 @@ errors:
message: "Error: %1 grouping '%2' already exists under '%3' sub-category.",
messageId: "SVC4563"
}
-#---------SVC4564------------------------------
+#---------SVC4564------------------------------
# %1 - product name
PRODUCT_NOT_FOUND: {
code: 404,
message: "Error: Requested '%1' product was not found.",
messageId: "SVC4564"
}
-#---------SVC4565------------------------------
-# %1 - "HEAT"
-# %2 - parameter type ("string" , "boolean" , "number")
+#---------SVC4565------------------------------
+# %1 - "HEAT"
+# %2 - parameter type ("string" , "boolean" , "number")
# %3 - parameter name
INVALID_HEAT_PARAMETER_VALUE: {
code: 400,
message: "Error: Invalid %1 artifact. Invalid %2 value set for '%3' parameter.",
messageId: "SVC4565"
}
-#---------SVC4566------------------------------
-# %1 - "HEAT"
-# %2 - parameter type ("string" , "boolean" , "number")
+#---------SVC4566------------------------------
+# %1 - "HEAT"
+# %2 - parameter type ("string" , "boolean" , "number")
INVALID_HEAT_PARAMETER_TYPE: {
code: 400,
message: "Error: Invalid %1 artifact. Unsupported '%2' parameter type.",
messageId: "SVC4566"
}
-#---------SVC4567------------------------------
-# %1 - "YANG_XML"
+#---------SVC4567------------------------------
+# %1 - "YANG_XML"
INVALID_XML: {
code: 400,
message: "Error: Uploaded XML file for %1 artifact is invalid.",
messageId: "SVC4567"
}
-#---------SVC4567------------------------------
-# %1 - "User Name and UserId"
+#---------SVC4567------------------------------
+# %1 - "User Name and UserId"
# %2 -"checked-out"/"in-certification"
CANNOT_DELETE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
message: "Error: User cannot be deleted. User '%1' has %2 projects.",
messageId: "SVC4567"
}
-#---------SVC4568------------------------------
-# %1 - "User Name and UserId"
+#---------SVC4568------------------------------
+# %1 - "User Name and UserId"
# %2 -"checked-out"/"in-certification"
CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS: {
code: 409,
message: "Error: Role cannot be changed. User '%1' has %2 projects.",
messageId: "SVC4568"
}
-#---------SVC4570------------------------------
+#---------SVC4570------------------------------
UPDATE_USER_ADMIN_CONFLICT: {
code: 409,
message: "Error: An administrator is not allowed to change his/her role.",
messageId: "SVC4570"
}
-#---------SVC4571------------------------------
+#---------SVC4571------------------------------
SERVICE_CANNOT_CONTAIN_SUBCATEGORY: {
code: 400,
message: "Error: Sub category cannot be defined for service",
messageId: "SVC4571"
}
-#---------SVC4572------------------------------
+#---------SVC4572------------------------------
# %1 - "Resource"/"Service"
COMPONENT_TOO_MUCH_CATEGORIES: {
code: 400,
message: "Error: %1 must have only 1 category",
messageId: "SVC4572"
}
-#---------SVC4574------------------------------
+#---------SVC4574------------------------------
RESOURCE_TOO_MUCH_SUBCATEGORIES: {
code: 400,
message: "Error: Resource must have only 1 sub category",
messageId: "SVC4574"
}
-#---------SVC4575------------------------------
+#---------SVC4575------------------------------
COMPONENT_MISSING_SUBCATEGORY: {
code: 400,
message: "Error: Missing sub category",
messageId: "SVC4575"
}
- #---------SVC4576------------------------------
+ #---------SVC4576------------------------------
# %1 - "component type"
UNSUPPORTED_ERROR: {
code: 400,
message: "Error : Requested component type %1 is unsupported.",
messageId: "SVC4576"
}
- #---------SVC4577------------------------------
+ #---------SVC4577------------------------------
# %1 - "resource type"
RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES: {
code: 409,
message: "Error : Resource of type %1 cannot contain resource instances.",
messageId: "SVC4577"
}
-#---------SVC4578------------------------------
+#---------SVC4578------------------------------
# %1 - "Resource"/"Service"
-# %2 - resource/service name
-# %3 - "artifact name"
+# %2 - resource/service name
+# %3 - "artifact name"
DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS: {
code: 400,
message: "Error: %1 '%2' already has a deployment artifact named '%3'.",
messageId: "SVC4578"
}
-#---------SVC4579------------------------------
+#---------SVC4579------------------------------
# %1 - "Category"/"Sub-Category"/"Group"
# %2 - category/sub-category/grouping name.
INVALID_GROUP_ASSOCIATION: {
@@ -1138,27 +1138,27 @@ errors:
message: "Error: Invalid group association. %1 '%2' was not found.",
messageId: "SVC4579"
}
-#---------SVC4580------------------------------
+#---------SVC4580------------------------------
EMPTY_PRODUCT_CONTACTS_LIST: {
code: 400,
message: "Error: Invalid content. At least one Product Contact has to be specified.",
messageId: "SVC4580"
}
-#---------SVC4581------------------------------
-# %1 - userId
+#---------SVC4581------------------------------
+# %1 - UserId
INVALID_PRODUCT_CONTACT: {
code: 400,
message: "Error: Invalid content. User '%1' cannot be set as Product Contact.",
messageId: "SVC4581"
}
-#---------SVC4582------------------------------
+#---------SVC4582------------------------------
# %1 - Product
# %2 - "abbreviated"/"full"
MISSING_ONE_OF_COMPONENT_NAMES: {
code: 400,
message: "Error: Invalid content. Missing %1 %2 name.",
messageId: "SVC4582"
- }
+ }
#---------SVC4583------------------------------
# %1 - "Icon"
# %2 - "resource"/"service"/"product"
@@ -1168,10 +1168,10 @@ errors:
messageId: "SVC4583"
}
#---------SVC4584------------------------------
-# %1 - service/VF name
+# %1 - service/VF name
# %2 - "service" /"VF"
# %3 - resource instance origin type
-# %4 - resource instance name
+# %4 - resource instance name
# %5 - requirement/capability
# %6 - requirement/capability name
# %7 - "fulfilled" (for req)/"consumed (for cap)"
@@ -1180,57 +1180,57 @@ errors:
message: "Error: Requested '%1' %2 is not ready for certification. %3 '%4' has to have %5 '%6' %7.",
messageId: "SVC4584"
}
-#---------SVC4585------------------------------
+#---------SVC4585------------------------------
INVALID_OCCURRENCES: {
code: 400,
message: "Error: Invalid occurrences format.",
messageId: "SVC4585"
}
-#---------SVC4586------------------------------
-#---------SVC4586------------------------------
+#---------SVC4586------------------------------
+#---------SVC4586------------------------------
INVALID_SERVICE_API_URL: {
code: 400,
message: 'Error: Invalid Service API URL. Please check whether your URL has a valid domain extension and does not contain the following characters - #?&@%+;,=$<>~^`\[]{}|"*!',
messageId: "SVC4586"
}
-#---------SVC4587------------------------------
-# %1 - Data type name
+#---------SVC4587------------------------------
+# %1 - Data type name
DATA_TYPE_ALREADY_EXIST: {
code: 409,
message: 'Error: Data type %1 already exists.',
messageId: "SVC4587"
}
-#---------SVC4588------------------------------
-# %1 - Data type name
+#---------SVC4588------------------------------
+# %1 - Data type name
DATA_TYPE_NOR_PROPERTIES_NEITHER_DERIVED_FROM: {
code: 400,
message: 'Error: Invalid Data type %1. Data type must have either a valid derived from declaration or at least one valid property',
messageId: "SVC4588"
}
-#---------SVC4589------------------------------
-# %1 - Data type name
+#---------SVC4589------------------------------
+# %1 - Data type name
DATA_TYPE_PROPERTIES_CANNOT_BE_EMPTY: {
code: 400,
message: "Error: Invalid Data type %1. 'properties' parameter cannot be empty if provided.",
messageId: "SVC4589"
}
-#---------SVC4590------------------------------
-# %1 - Property type name
+#---------SVC4590------------------------------
+# %1 - Property type name
# %2 - Property name
INVALID_PROPERTY_TYPE: {
code: 400,
message: "Error: Invalid Property type %1 in property %2.",
messageId: "SVC4590"
}
-#---------SVC4591------------------------------
+#---------SVC4591------------------------------
# %1 - Property inner type
-# %2 - Property name
+# %2 - Property name
INVALID_PROPERTY_INNER_TYPE: {
code: 400,
message: "Error: Invalid property inner type %1, in property %2",
messageId: "SVC4591"
}
-#---------SVC4592------------------------------
+#---------SVC4592------------------------------
# %1 - component instance name
# %2 - "resource instance"/"service instance"
COMPONENT_INSTANCE_NOT_FOUND: {
@@ -1238,11 +1238,11 @@ errors:
message: "Error: Requested '%1' %2 was not found.",
messageId: "SVC4592"
}
-#---------SVC4593------------------------------
+#---------SVC4593------------------------------
# %1 - component instance name
# %2 - "resource instance"/"service instance"
# %3 - "resource/"service"/"product"
-# %4 - container name
+# %4 - container name
COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER: {
code: 404,
message: "Error: Requested '%1' %2 was not found on the %3 '%4'.",
@@ -1259,20 +1259,20 @@ errors:
#---------SVC4595------------------------------
#%1 - requirement / capability
#%2 - requirement name
-#%3 - parent containing the requirement
+#%3 - parent containing the requirement
IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED: {
code: 400,
message: "Error: Imported TOSCA template contains %1 '%2' that is already defined by derived template %3.",
messageId: "SVC4595"
}
-#---------SVC4596------------------------------
+#---------SVC4596------------------------------
# %1 - Data type name
DATA_TYPE_DERIVED_IS_MISSING: {
code: 400,
message: "Error: Invalid Content. The ancestor data type %1 cannot be found in the system.",
messageId: "SVC4596"
}
-#---------SVC4597------------------------------
+#---------SVC4597------------------------------
# %1 - Data type name
# %2 - Property names
DATA_TYPE_PROPERTY_ALREADY_DEFINED_IN_ANCESTOR: {
@@ -1280,14 +1280,14 @@ errors:
message: "Error: Invalid Content. The data type %1 contains properties named %2 which are already defined in one of its ancestors.",
messageId: "SVC4597"
}
-#---------SVC4598------------------------------
+#---------SVC4598------------------------------
# %1 - Data type name
DATA_TYPE_DUPLICATE_PROPERTY: {
code: 400,
message: "Error: Invalid Content. The data type %1 contains duplicate property.",
messageId: "SVC4598"
}
-#---------SVC4599------------------------------
+#---------SVC4599------------------------------
# %1 - Data type name
# %2 - Property names
DATA_TYPE_PROEPRTY_CANNOT_HAVE_SAME_TYPE_OF_DATA_TYPE: {
@@ -1295,14 +1295,14 @@ errors:
message: "Error: Invalid Content. The data type %1 contains properties %2 which their type is this data type.",
messageId: "SVC4599"
}
-#---------SVC4600------------------------------
+#---------SVC4600------------------------------
# %1 - Data type name
DATA_TYPE_CANNOT_HAVE_PROPERTIES: {
code: 400,
message: "Error: Invalid Content. The data type %1 cannot have properties since it is of type scalar",
messageId: "SVC4600"
}
-#---------SVC4601------------------------------
+#---------SVC4601------------------------------
NOT_TOPOLOGY_TOSCA_TEMPLATE: {
code: 400,
message: "Error: TOSCA yaml file %1 cannot be modeled to VF as it does not contain 'topology_template.",
@@ -1317,7 +1317,7 @@ errors:
message: "Error: TOSCA yaml file '%1' contains node_template '%2' of type '%3' that does not represent existing VFC/CP/VL",
messageId: "SVC4602"
}
-#---------SVC4603------------------------------
+#---------SVC4603------------------------------
# %1 - component type
# %2 - component name
# %3 - state
@@ -1326,21 +1326,21 @@ errors:
message: "Error: Component instance of %1 can not be created because the component '%2' is in an illegal state %3.",
messageId: "SVC4603"
}
-#---------SVC4604------------------------------
+#---------SVC4604------------------------------
# %1 - csar file name
CSAR_INVALID: {
code: 400,
message: "Error: TOSCA CSAR '%1' is invalid. 'TOSCA-Metadata/Tosca.meta' file must be provided.",
messageId: "SVC4604"
}
-#---------SVC4605------------------------------
+#---------SVC4605------------------------------
# %1 - csar file name
CSAR_INVALID_FORMAT: {
code: 400,
message: "Error: TOSCA CSAR '%1' is invalid. Invalid 'TOSCA-Metadata/Tosca.meta' file format.",
messageId: "SVC4605"
}
-#---------SVC4606------------------------------
+#---------SVC4606------------------------------
# %1 - property name
# %2 - property type
# %3 - property innerType
@@ -1350,14 +1350,14 @@ errors:
message: "Error: Invalid default value of property %1. Data type is %2 with inner type %3 and default value found is %4.",
messageId: "SVC4606"
}
-#---------SVC4607------------------------------
+#---------SVC4607------------------------------
# %1 - csar file name
CSAR_NOT_FOUND: {
code: 400,
message: "Error: TOSCA CSAR '%1' is not found.",
messageId: "SVC4607"
}
-#---------SVC4608------------------------------
+#---------SVC4608------------------------------
# %1 - artifact name
# %2 - component type
# %3 - actual component type
@@ -1367,14 +1367,14 @@ errors:
messageId: "SVC4608"
}
-#---------SVC4609------------------------------
-# %1 - "INVALID_JSON"
+#---------SVC4609------------------------------
+# %1 - "INVALID_JSON"
INVALID_JSON: {
code: 400,
message: "Error: Uploaded JSON file for %1 artifact is invalid.",
messageId: "SVC4609"
}
-#---------SVC4610------------------------------
+#---------SVC4610------------------------------
# %1 - csar file name
# %2 - missing file name
YAML_NOT_FOUND_IN_CSAR: {
@@ -1382,21 +1382,21 @@ errors:
message: "Error - TOSCA CSAR %1 is invalid. TOSCA-Metadata/Tosca.meta refers to file %2 that is not provided.",
messageId: "SVC4610"
}
-#---------SVC4611------------------------------
+#---------SVC4611------------------------------
# %1 - group name
GROUP_MEMBER_EMPTY: {
code: 400,
message: "Error: Invalid Content. Group %1 member list was provided but does not have values",
messageId: "SVC4611"
}
-#---------SVC4612------------------------------
-# %1 - group name
+#---------SVC4612------------------------------
+# %1 - group name
GROUP_TYPE_ALREADY_EXIST: {
code: 409,
message: 'Error: Group type %1 already exists.',
messageId: "SVC4612"
}
-#---------SVC4613------------------------------
+#---------SVC4613------------------------------
# %1 - group name
# %2 - VF name(component name)
# %3 - actual component type [VF]
@@ -1404,15 +1404,15 @@ errors:
code: 409,
message: "Error: Group with name '%1' already exists in %2 %3.",
messageId: "SVC4613"
- }
-#---------SVC4614------------------------------
+ }
+#---------SVC4614------------------------------
# %1 - group type
GROUP_TYPE_IS_INVALID: {
code: 400,
message: "Error: Invalid content. Group type %1 does not exist",
messageId: "SVC4614"
}
-#---------SVC4615------------------------------
+#---------SVC4615------------------------------
# %1 - group name
GROUP_MISSING_GROUP_TYPE: {
code: 400,
@@ -1428,7 +1428,7 @@ errors:
code: 400,
message: "Error: Member '%1' listed in group '%2' is not part of '%3' %4.",
messageId: "SVC4616"
- }
+ }
#---------SVC4617------------------------------
# %1 - member name
# %2 - group name
@@ -1438,7 +1438,7 @@ errors:
message: "Error: member %1 listed in group %2 is not part of allowed members of group type %3.",
messageId: "SVC4617"
}
-#---------SVC4618------------------------------
+#---------SVC4618------------------------------
# %1 - missing file name
# %2 - csar file name
ARTIFACT_NOT_FOUND_IN_CSAR: {
@@ -1446,7 +1446,7 @@ errors:
message: "Error: artifact %1 is defined in CSAR %2 manifest but is not provided",
messageId: "SVC4618"
}
-#---------SVC4619------------------------------
+#---------SVC4619------------------------------
# %1 - artifact name
# %2 - artifact type
# %3 - existing artifact type
@@ -1455,23 +1455,23 @@ errors:
message: "Error: artifact %1 in type %2 already exists in type %3.",
messageId: "SVC4619"
}
-#---------SVC4620------------------------------
+#---------SVC4620------------------------------
FAILED_RETRIVE_ARTIFACTS_TYPES: {
code: 400,
message: "Error: Failed to retrieve list of suported artifact types.",
messageId: "SVC4620"
}
-#---------SVC4621------------------------------
+#---------SVC4621------------------------------
# %1 - artifact name
-# %2 - master
+# %2 - master
ARTIFACT_ALRADY_EXIST_IN_MASTER_IN_CSAR: {
code: 400,
message: "Error: artifact %1 already exists in master %2 .",
messageId: "SVC4621"
}
-#---------SVC4622------------------------------
+#---------SVC4622------------------------------
# %1 - artifact name
-# %2 - artifact type
+# %2 - artifact type
# %3 - master name
# %4 - master type
ARTIFACT_NOT_VALID_IN_MASTER: {
@@ -1479,9 +1479,9 @@ errors:
message: "Error: artifact %1 in type %2 can not be exists under master %3 in type %4.",
messageId: "SVC4622"
}
-#---------SVC4623------------------------------
+#---------SVC4623------------------------------
# %1 - artifact name
-# %2 - artifact type
+# %2 - artifact type
# %3 - env name
# %4 - existing env
ARTIFACT_NOT_VALID_ENV: {
@@ -1489,7 +1489,7 @@ errors:
message: "Error: Artifact %1 in type %2 with env %3 already exists with another env %4",
messageId: "SVC4623"
}
-#---------SVC4624------------------------------
+#---------SVC4624------------------------------
# %1 - groups names
# %2 - VF name
# %3 - component type [VF ]
@@ -1498,14 +1498,14 @@ errors:
message: "Error: Invalid Content. The groups '%1' cannot be found under %2 %3.",
messageId: "SVC4624"
}
-#---------SVC4625------------------------------
+#---------SVC4625------------------------------
# %1 - groups name
GROUP_ARTIFACT_ALREADY_ASSOCIATED: {
code: 400,
message: "Error: Invalid Content. Artifact already associated to group '%1'.",
messageId: "SVC4625"
}
-#---------SVC4626------------------------------
+#---------SVC4626------------------------------
# %1 - groups name
GROUP_ARTIFACT_ALREADY_DISSOCIATED: {
code: 400,
@@ -1521,7 +1521,7 @@ errors:
message: "Error: property %1 listed in group %2 is not exist in group type %3.",
messageId: "SVC4627"
}
-#---------SVC4628------------------------------
+#---------SVC4628------------------------------
# %1 - csarUUID
# %2 - VF name
VSP_ALREADY_EXISTS: {
@@ -1529,14 +1529,14 @@ errors:
message: "Error: The VSP with UUID %1 was already imported for VF %2. Please select another or update the existing VF.",
messageId: "SVC4628"
}
-#---------SVC4629------------------------------
+#---------SVC4629------------------------------
# %1 - VF name
MISSING_CSAR_UUID: {
code: 400,
message: "Error: The Csar UUID or payload name is missing for VF %1.",
messageId: "SVC4629"
}
-#---------SVC4630------------------------------
+#---------SVC4630------------------------------
# %1 - VF name
# %2 - new csarUUID
# %3 - old csarUUID
@@ -1545,8 +1545,8 @@ errors:
message: "Error: Resource %1 cannot be updated using CsarUUID %2 since the resource is linked to a different VSP with csarUUID %3.",
messageId: "SVC4630"
}
-#---------SVC4631------------------------------
-# %1 - policy name
+#---------SVC4631------------------------------
+# %1 - policy name
POLICY_TYPE_ALREADY_EXIST: {
code: 409,
message: "Error: Policy type %1 already exists.",
@@ -1593,7 +1593,7 @@ errors:
code: 404,
message: "Error: Requested '%1' attribute was not found.",
messageId: "SVC4637"
- }
+ }
#-----------SVC4638---------------------------
#%1 - attribute name
ATTRIBUTE_ALREADY_EXIST: {
@@ -1661,7 +1661,7 @@ errors:
message: "Error: Invalid Content. VF Module name '%1' contains invalid characters",
messageId: "SVC4646"
}
-
+
#---------SVC4647------------------------------
# %1 - "modifiedName"
INVALID_VF_MODULE_NAME_MODIFICATION: {
@@ -1699,23 +1699,23 @@ errors:
message: "Error: Once resource is certified, derived_from can be changed only to a sibling",
messageId: "SVC4651"
}
-#---------SVC4652------------------------------
+#---------SVC4652------------------------------
# %1 - resource/service
COMPONENT_INVALID_SUBCATEGORY: {
code: 400,
message: "Error: Invalid Content. Invalid %1 sub category.",
messageId: "SVC4652"
}
-#---------SVC4653------------------------------
-# %1 - group instance uniqueId
+#---------SVC4653------------------------------
+# %1 - group instance uniqueId
# %2 - service uniqueId
GROUP_INSTANCE_NOT_FOUND_ON_COMPONENT_INSTANCE: {
code: 404,
message: "Error: Requested group instance %1 was not found on component %2.",
messageId: "SVC4653"
}
-#---------SVC4654------------------------------
-# %1 - group property name
+#---------SVC4654------------------------------
+# %1 - group property name
# %2 - valid min limit value
# %3 - valid max limit value
INVALID_GROUP_MIN_MAX_INSTANCES_PROPERTY_VALUE: {
@@ -1723,8 +1723,8 @@ errors:
message: "Error: Value of %1 must be not higher than %2, and not lower than %3.",
messageId: "SVC4654"
}
-#---------SVC4655------------------------------
-# %1 - group property name
+#---------SVC4655------------------------------
+# %1 - group property name
# %2 - valid min limit value
# %3 - valid max limit value
INVALID_GROUP_INITIAL_COUNT_PROPERTY_VALUE: {
@@ -1732,15 +1732,15 @@ errors:
message: "Error: Value of %1 must be between %2 and %3.",
messageId: "SVC4655"
}
-#---------SVC4656------------------------------
-# %1 - group property name
+#---------SVC4656------------------------------
+# %1 - group property name
# %2 - lower/higher
# %3 - valid max/min value
INVALID_GROUP_PROPERTY_VALUE_LOWER_HIGHER: {
code: 400,
message: "Error: Value of %1 must be %2 or equals to %3.",
messageId: "SVC4656"
- }
+ }
#---------SVC4657------------------------------
# %1 - certificationRequest / startTesting
RESOURCE_VFCMT_LIFECYCLE_STATE_NOT_VALID: {
@@ -1752,7 +1752,7 @@ errors:
# %1 – asset type [service / resource ]
# %2 – main asset uuid
# %3 – not found asset type [service / resource]
-# %4 – not found asset name
+# %4 – not found asset name
ASSET_NOT_FOUND_DURING_CSAR_CREATION: {
code: 400,
message: "Error: CSAR packaging failed for %1 %2. %3 %4 was not found",
@@ -1761,10 +1761,87 @@ errors:
#---------SVC4659------------------------------
# %1 – asset type [service / resource ]
# %2 – main asset uuid
-# %3 – Artifact name
+# %3 – Artifact name
# %4 – Artifact uuid
ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION: {
code: 400,
- message: " Error: CSAR packaging failed for %1 %2. Artifact %3 [%4] was not found",
+ message: "Error: CSAR packaging failed for %1 %2. Artifact %3 [%4] was not found",
messageId: "SVC4659"
+ }
+#---------SVC4660------------------------------
+# %1 - assetType
+# %2 - matching generic node type name
+ GENERIC_TYPE_NOT_FOUND: {
+ code: 404,
+ message: "Creation of %1 failed. Generic type %2 was not found",
+ messageId: "SVC4660"
+ }
+#---------SVC4661------------------------------
+# %1 - assetType
+# %2 - matching generic node type name
+ TOSCA_SCHEMA_FILES_NOT_FOUND: {
+ code: 400,
+ message: "Error: CSAR packaging failed. TOSCA schema files for SDC-Version: %1 and Conformance-Level %2 were not found",
+ messageId: "SVC4661"
+ }
+#---------SVC4662------------------------------
+# %1 - file name
+# %2 - parser error
+ TOSCA_PARSE_ERROR: {
+ code: 400,
+ message: "Error: Invalid TOSCA template in file %1. %2",
+ messageId: "SVC4662"
+ }
+#---------SVC4663------------------------------
+# %1 - max length
+ RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Resource vendor model number exceeds limit of %1 characters.",
+ messageId: "SVC4663"
+ }
+#---------SVC4664------------------------------
+ INVALID_RESOURCE_VENDOR_MODEL_NUMBER: {
+ code: 400,
+ message: 'Error: Invalid Content. Resource vendor model number is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4664"
+ }
+#---------SVC4665------------------------------
+# %1 - max length
+ SERVICE_TYPE_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Service type exceeds limit of %1 characters.",
+ messageId: "SVC4665"
+ }
+#---------SVC4666------------------------------
+ INVALID_SERVICE_TYPE: {
+ code: 400,
+ message: 'Error: Invalid Content. Serivce type is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4666"
+ }
+#---------SVC4667------------------------------
+# %1 - max length
+ SERVICE_ROLE_EXCEEDS_LIMIT: {
+ code: 400,
+ message: "Error: Invalid Content. Service role exceeds limit of %1 characters.",
+ messageId: "SVC4667"
+ }
+#---------SVC4668------------------------------
+ INVALID_SERVICE_ROLE: {
+ code: 400,
+ message: 'Error: Invalid Content. Service role is not allowed to contain characters like <>:"\/|?* and space characters other than regular space.',
+ messageId: "SVC4668"
+ }
+
+ #---------SVC4669-----------------------------
+ INVALID_RESOURCE_TYPE: {
+ code: 400,
+ message: "Error: Invalid resource type.",
+ messageId: "SVC4669"
+ }
+
+ #---------SVC4670------------------------------
+ ARTIFACT_NAME_INVALID: {
+ code: 400,
+ message: "Error: Artifact name is invalid.",
+ messageId: "SVC4670"
} \ No newline at end of file
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java
index 0a7a009ad4..4ae3e61841 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java
@@ -27,7 +27,9 @@ public enum ActionStatus {
// CapabilityType related
CAPABILITY_TYPE_ALREADY_EXIST, MISSING_CAPABILITY_TYPE, REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, IMPORT_DUPLICATE_REQ_CAP_NAME, IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED,
// Resource related
- RESOURCE_NOT_FOUND, MISSING_DERIVED_FROM_TEMPLATE, PARENT_RESOURCE_NOT_FOUND, PARENT_RESOURCE_DOES_NOT_EXTEND, INVALID_DEFAULT_VALUE, INVALID_COMPLEX_DEFAULT_VALUE, MULTIPLE_PARENT_RESOURCE_FOUND, INVALID_RESOURCE_PAYLOAD, INVALID_TOSCA_FILE_EXTENSION, INVALID_YAML_FILE, INVALID_TOSCA_TEMPLATE, NOT_RESOURCE_TOSCA_TEMPLATE, NOT_SINGLE_RESOURCE, INVALID_RESOURCE_NAMESPACE, RESOURCE_ALREADY_EXISTS, INVALID_RESOURCE_CHECKSUM, RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, NO_ASSETS_FOUND, GENERIC_TYPE_NOT_FOUND, TOSCA_PARSE_ERROR,
+ RESOURCE_NOT_FOUND, MISSING_DERIVED_FROM_TEMPLATE, PARENT_RESOURCE_NOT_FOUND, PARENT_RESOURCE_DOES_NOT_EXTEND, INVALID_DEFAULT_VALUE, INVALID_COMPLEX_DEFAULT_VALUE, MULTIPLE_PARENT_RESOURCE_FOUND, INVALID_RESOURCE_PAYLOAD, INVALID_TOSCA_FILE_EXTENSION, INVALID_YAML_FILE, INVALID_TOSCA_TEMPLATE, NOT_RESOURCE_TOSCA_TEMPLATE, NOT_SINGLE_RESOURCE, INVALID_RESOURCE_NAMESPACE, RESOURCE_ALREADY_EXISTS, INVALID_RESOURCE_CHECKSUM, RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, NO_ASSETS_FOUND, GENERIC_TYPE_NOT_FOUND,INVALID_RESOURCE_TYPE, TOSCA_PARSE_ERROR,
+ // Service related
+ SERVICE_TYPE_EXCEEDS_LIMIT, INVALID_SERVICE_TYPE, SERVICE_ROLE_EXCEEDS_LIMIT, INVALID_SERVICE_ROLE,
// Component name related
COMPONENT_NAME_ALREADY_EXIST, COMPONENT_NAME_EXCEEDS_LIMIT, MISSING_COMPONENT_NAME, INVALID_COMPONENT_NAME,
// Component description related
@@ -39,7 +41,7 @@ public enum ActionStatus {
// contactId related
COMPONENT_MISSING_CONTACT, COMPONENT_INVALID_CONTACT,
// Vendor related
- VENDOR_NAME_EXCEEDS_LIMIT, VENDOR_RELEASE_EXCEEDS_LIMIT, INVALID_VENDOR_NAME, INVALID_VENDOR_RELEASE, MISSING_VENDOR_NAME, MISSING_VENDOR_RELEASE,
+ VENDOR_NAME_EXCEEDS_LIMIT, VENDOR_RELEASE_EXCEEDS_LIMIT, INVALID_VENDOR_NAME, INVALID_VENDOR_RELEASE, MISSING_VENDOR_NAME, MISSING_VENDOR_RELEASE, RESOURCE_VENDOR_MODEL_NUMBER_EXCEEDS_LIMIT, INVALID_RESOURCE_VENDOR_MODEL_NUMBER,
// Category related
COMPONENT_MISSING_CATEGORY, COMPONENT_INVALID_CATEGORY, COMPONENT_ELEMENT_INVALID_NAME_FORMAT, COMPONENT_ELEMENT_INVALID_NAME_LENGTH, COMPONENT_CATEGORY_ALREADY_EXISTS, COMPONENT_CATEGORY_NOT_FOUND, COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY, COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY,
// Service API URL
@@ -71,7 +73,7 @@ public enum ActionStatus {
GROUP_MEMBER_EMPTY, GROUP_TYPE_ALREADY_EXIST,
// CSAR
- MISSING_CSAR_UUID, CSAR_INVALID, CSAR_INVALID_FORMAT, CSAR_NOT_FOUND, YAML_NOT_FOUND_IN_CSAR, VSP_ALREADY_EXISTS, RESOURCE_LINKED_TO_DIFFERENT_VSP, RESOURCE_FROM_CSAR_NOT_FOUND, AAI_ARTIFACT_GENERATION_FAILED, ASSET_NOT_FOUND_DURING_CSAR_CREATION, ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, TOSCA_SCHEMA_FILES_NOT_FOUND,
+ MISSING_CSAR_UUID, CSAR_INVALID, CSAR_INVALID_FORMAT, CSAR_NOT_FOUND, YAML_NOT_FOUND_IN_CSAR, VSP_ALREADY_EXISTS, RESOURCE_LINKED_TO_DIFFERENT_VSP, RESOURCE_FROM_CSAR_NOT_FOUND, AAI_ARTIFACT_GENERATION_FAILED, ASSET_NOT_FOUND_DURING_CSAR_CREATION, ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, TOSCA_SCHEMA_FILES_NOT_FOUND, ARTIFACT_NAME_INVALID,
// Group
GROUP_HAS_CYCLIC_DEPENDENCY, GROUP_ALREADY_EXIST, GROUP_TYPE_IS_INVALID, GROUP_MISSING_GROUP_TYPE, GROUP_INVALID_COMPONENT_INSTANCE, GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, GROUP_IS_MISSING, GROUP_ARTIFACT_ALREADY_ASSOCIATED, GROUP_ARTIFACT_ALREADY_DISSOCIATED, GROUP_PROPERTY_NOT_FOUND, INVALID_VF_MODULE_NAME, INVALID_VF_MODULE_NAME_MODIFICATION, INVALID_VF_MODULE_TYPE,
@@ -86,6 +88,7 @@ public enum ActionStatus {
// Inputs
INPUT_IS_NOT_CHILD_OF_COMPONENT,
+ CFVC_LOOP_DETECTED,
;
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/MigrationTasksAccessor.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/MigrationTasksAccessor.java
new file mode 100644
index 0000000000..e548a594d9
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/MigrationTasksAccessor.java
@@ -0,0 +1,17 @@
+package org.openecomp.sdc.be.dao.cassandra;
+
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.mapping.annotations.Accessor;
+import com.datastax.driver.mapping.annotations.Param;
+import com.datastax.driver.mapping.annotations.Query;
+
+@Accessor
+public interface MigrationTasksAccessor {
+
+ @Query("SELECT minor_version FROM sdcrepository.migrationTasks WHERE major_version = :majorVersion order by minor_version desc limit 1")
+ ResultSet getLatestMinorVersion(@Param("majorVersion") Long majorVersion);
+
+ @Query("DELETE FROM sdcrepository.migrationTasks WHERE major_version = :majorVersion")
+ void deleteTasksForMajorVersion(@Param("majorVersion") Long majorVersion);
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/MigrationTasksDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/MigrationTasksDao.java
new file mode 100644
index 0000000000..89ad9662fa
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/MigrationTasksDao.java
@@ -0,0 +1,73 @@
+package org.openecomp.sdc.be.dao.cassandra;
+
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.mapping.Mapper;
+import com.datastax.driver.mapping.MappingManager;
+import fj.data.Either;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.resources.data.MigrationTaskEntry;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import java.math.BigInteger;
+
+@Component("sdc-migration-tasks-cassandra-dao")
+public class MigrationTasksDao extends CassandraDao {
+
+ private static Logger logger = LoggerFactory.getLogger(MigrationTasksDao.class.getName());
+ private MigrationTasksAccessor migrationTasksAccessor;
+ private Mapper<MigrationTaskEntry> migrationTaskMapper;
+
+ @PostConstruct
+ public void init() {
+ String keyspace = AuditingTypesConstants.REPO_KEYSPACE;
+ if (client.isConnected()) {
+ Either<ImmutablePair<Session, MappingManager>, CassandraOperationStatus> result = client.connect(keyspace);
+ if (result.isLeft()) {
+ session = result.left().value().left;
+ manager = result.left().value().right;
+ migrationTasksAccessor = manager.createAccessor(MigrationTasksAccessor.class);
+ migrationTaskMapper = manager.mapper(MigrationTaskEntry.class);
+ logger.info("** migrationTasksAccessor created");
+ } else {
+ logger.info("** migrationTasksAccessor failed");
+ throw new RuntimeException("Artifact keyspace [" + keyspace + "] failed to connect with error : "
+ + result.right().value());
+ }
+ } else {
+ logger.info("** Cassandra client isn't connected");
+ logger.info("** migrationTasksAccessor created, but not connected");
+ }
+ }
+
+ public BigInteger getLatestMinorVersion(BigInteger majorVersion) {
+ try {
+ ResultSet latestMinorVersion = migrationTasksAccessor.getLatestMinorVersion(majorVersion.longValue());
+ Row minorVersionRow = latestMinorVersion.one();
+ return minorVersionRow == null ? BigInteger.valueOf(Long.MIN_VALUE) : BigInteger.valueOf(minorVersionRow.getLong(0));
+ } catch (RuntimeException e) {
+ logger.error("failed to get latest minor version for major version {}", majorVersion, e);
+ throw e;
+ }
+ }
+
+ public void deleteAllTasksForVersion(BigInteger majorVersion) {
+ try {
+ migrationTasksAccessor.deleteTasksForMajorVersion(majorVersion.longValue());
+ } catch (RuntimeException e) {
+ logger.error("failed to delete tasks for major version {}", majorVersion, e);
+ throw e;
+ }
+ }
+
+ public void createMigrationTask(MigrationTaskEntry migrationTask) {
+ migrationTaskMapper.save(migrationTask);
+ }
+
+
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java
index 8fb594f2ff..f6fd29bd1f 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/Table.java
@@ -20,24 +20,7 @@
package org.openecomp.sdc.be.dao.cassandra.schema;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.ArtifactTableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.AuthEventTableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.CategoryEventTableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.ComponentCacheTableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.ConsumerEventTableDefinition;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribDeployEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribDownloadEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribEngineEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribNotifEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.DistribStatusEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.ExternalApiEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetCatHierEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUebClusterEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.GetUsersListEventTableDesc;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.ResAdminEventTableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.SdcSchemaFilesTableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.UserAccessEventTableDescription;
-import org.openecomp.sdc.be.dao.cassandra.schema.tables.UserAdminEventTableDescription;
+import org.openecomp.sdc.be.dao.cassandra.schema.tables.*;
public enum Table {
@@ -58,8 +41,8 @@ public enum Table {
GET_CATEGORY_HIERARCHY_EVENT(new GetCatHierEventTableDesc()),
EXTERNAL_API_EVENT(new ExternalApiEventTableDesc()),
COMPONENT_CACHE(new ComponentCacheTableDescription()),
- SDC_SCHEMA_FILES(new SdcSchemaFilesTableDescription());
-
+ SDC_SCHEMA_FILES(new SdcSchemaFilesTableDescription()),
+ SDC_REPO(new MigrationTasksTableDescription());
ITableDescription tableDescription;
Table(ITableDescription tableDescription) {
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/MigrationTasksTableDescription.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/MigrationTasksTableDescription.java
new file mode 100644
index 0000000000..f7506f77e1
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/cassandra/schema/tables/MigrationTasksTableDescription.java
@@ -0,0 +1,81 @@
+package org.openecomp.sdc.be.dao.cassandra.schema.tables;
+
+import com.datastax.driver.core.DataType;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.dao.cassandra.schema.ITableDescription;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.openecomp.sdc.be.dao.cassandra.schema.tables.MigrationTasksTableDescription.SdcRepoFieldsDescription.MAJOR_VERSION;
+import static org.openecomp.sdc.be.dao.cassandra.schema.tables.MigrationTasksTableDescription.SdcRepoFieldsDescription.MINOR_VERSION;
+
+public class MigrationTasksTableDescription implements ITableDescription {
+
+ private static final String MIGRATION_TASKS_TABLE = "migrationTasks";
+
+ @Override
+ public List<ImmutablePair<String, DataType>> primaryKeys() {
+ return Collections.singletonList(ImmutablePair.of(MAJOR_VERSION.getFieldName(), MAJOR_VERSION.getFieldType()));
+ }
+
+ @Override
+ public List<ImmutablePair<String, DataType>> clusteringKeys() {
+ return Collections.singletonList(ImmutablePair.of(MINOR_VERSION.getFieldName(), MINOR_VERSION.getFieldType()));
+ }
+
+ @Override
+ public Map<String, ImmutablePair<DataType, Boolean>> getColumnDescription() {
+ Map<String, ImmutablePair<DataType, Boolean>> columns = new HashMap<>();
+ Arrays.stream(SdcRepoFieldsDescription.values())
+ .filter(column -> !column.equals(MAJOR_VERSION) && !column.equals(MINOR_VERSION))
+ .forEach(column -> columns.put(column.getFieldName(), ImmutablePair.of(column.getFieldType(), column.isIndexed())));
+ return columns;
+ }
+
+ @Override
+ public String getKeyspace() {
+ return AuditingTypesConstants.REPO_KEYSPACE;
+ }
+
+ @Override
+ public String getTableName() {
+ return MIGRATION_TASKS_TABLE;
+ }
+
+ enum SdcRepoFieldsDescription {
+ MAJOR_VERSION("major_version", DataType.bigint(), true),
+ MINOR_VERSION("minor_version", DataType.bigint(), false),
+ TIMESTAMP("timestamp", DataType.timestamp(), false),
+ NAME("task_name", DataType.varchar(), false),
+ STATUS("task_status", DataType.varchar(), false),
+ MESSAGE("msg", DataType.varchar(), false),
+ EXECUTION_TIME("execution_time", DataType.cdouble(), false);
+
+ private String fieldName;
+ private boolean isIndexed;
+ private DataType fieldType;
+
+ SdcRepoFieldsDescription(String fieldName, DataType dataType, boolean indexed ) {
+ this.fieldName = fieldName;
+ this.fieldType = dataType;
+ this.isIndexed = indexed;
+ }
+
+ public String getFieldName() {
+ return fieldName;
+ }
+
+ public boolean isIndexed() {
+ return isIndexed;
+ }
+
+ public DataType getFieldType() {
+ return fieldType;
+ }
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java
index 2d9c029ea9..387b413dd5 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java
@@ -456,7 +456,11 @@ public class TitanDao {
}
if (hasNotProps != null && !hasNotProps.isEmpty()) {
for (Map.Entry<GraphPropertyEnum, Object> entry : hasNotProps.entrySet()) {
- query = query.hasNot(entry.getKey().getProperty(), entry.getValue());
+ if(entry.getValue() instanceof List){
+ buildMultipleNegateQueryFromList(entry, query);
+ }else{
+ query = query.hasNot(entry.getKey().getProperty(), entry.getValue());
+ }
}
}
Iterable<TitanVertex> vertices = query.vertices();
@@ -499,6 +503,15 @@ public class TitanDao {
}
+
+ private void buildMultipleNegateQueryFromList(Map.Entry<GraphPropertyEnum, Object> entry, TitanGraphQuery query){
+ List<Object> negateList = (List<Object>) entry.getValue();
+ for (Object listItem : negateList) {
+ query.hasNot(entry.getKey().getProperty(), listItem);
+ }
+ }
+
+
/**
*
* @param parentVertex
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java
index 001544c4a4..3018915066 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/EdgeLabelEnum.java
@@ -67,4 +67,8 @@ public enum EdgeLabelEnum {
}
return null;
}
+
+ public boolean isInstanceArtifactsLabel() {
+ return this.equals(INSTANCE_ARTIFACTS) || this.equals(INST_DEPLOYMENT_ARTIFACTS);
+ }
}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/MigrationTaskEntry.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/MigrationTaskEntry.java
new file mode 100644
index 0000000000..08376b616f
--- /dev/null
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/MigrationTaskEntry.java
@@ -0,0 +1,92 @@
+package org.openecomp.sdc.be.resources.data;
+
+import com.datastax.driver.mapping.annotations.ClusteringColumn;
+import com.datastax.driver.mapping.annotations.Column;
+import com.datastax.driver.mapping.annotations.PartitionKey;
+import com.datastax.driver.mapping.annotations.Table;
+
+import java.math.BigInteger;
+import java.util.Date;
+
+@Table(keyspace = "sdcrepository", name = "migrationTasks")
+public class MigrationTaskEntry {
+
+ @PartitionKey(0)
+ @Column(name = "major_version")
+ private Long majorVersion;
+
+ @ClusteringColumn
+ @Column(name = "minor_version")
+ private Long minorVersion;
+
+ @Column(name = "timestamp")
+ private Date timestamp;
+
+ @Column(name = "task_name")
+ private String taskName;
+
+ @Column(name = "execution_time")
+ private double executionTime;
+
+ @Column(name = "task_status")
+ private String taskStatus;
+
+ @Column(name = "msg")
+ private String message;
+
+ public void setMajorVersion(Long majorVersion) {
+ this.majorVersion = majorVersion;
+ }
+
+ public void setMinorVersion(Long minorVersion) {
+ this.minorVersion = minorVersion;
+ }
+
+ public void setTimestamp(Date timestamp) {
+ this.timestamp = timestamp;
+ }
+
+ public void setTaskName(String taskName) {
+ this.taskName = taskName;
+ }
+
+ public void setTaskStatus(String taskStatus) {
+ this.taskStatus = taskStatus;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public void setExecutionTime(double executionTime) {
+ this.executionTime = executionTime;
+ }
+
+ public Long getMajorVersion() {
+ return majorVersion;
+ }
+
+ public Long getMinorVersion() {
+ return minorVersion;
+ }
+
+ public Date getTimestamp() {
+ return timestamp;
+ }
+
+ public String getTaskName() {
+ return taskName;
+ }
+
+ public String getTaskStatus() {
+ return taskStatus;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public double getExecutionTime() {
+ return executionTime;
+ }
+}
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java
index 01774ca63f..9f25932b37 100644
--- a/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java
+++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/resources/data/auditing/AuditingTypesConstants.java
@@ -22,28 +22,29 @@ package org.openecomp.sdc.be.resources.data.auditing;
public interface AuditingTypesConstants {
- public static final String ARTIFACT_KEYSPACE = "sdcartifact";
- public static final String AUDIT_KEYSPACE = "sdcaudit";
- public static final String COMPONENT_KEYSPACE = "sdccomponent";
- public static final String TITAN_KEYSPACE = "titan";
+ String ARTIFACT_KEYSPACE = "sdcartifact";
+ String REPO_KEYSPACE = "sdcrepository";
+ String AUDIT_KEYSPACE = "sdcaudit";
+ String COMPONENT_KEYSPACE = "sdccomponent";
+ String TITAN_KEYSPACE = "titan";
- public static final String USER_ADMIN_EVENT_TYPE = "useradminevent";
- public static final String USER_ACCESS_EVENT_TYPE = "useraccessevent";
- public static final String RESOURCE_ADMIN_EVENT_TYPE = "resourceadminevent";
- public static final String DISTRIBUTION_DOWNLOAD_EVENT_TYPE = "distributiondownloadevent";
+ String USER_ADMIN_EVENT_TYPE = "useradminevent";
+ String USER_ACCESS_EVENT_TYPE = "useraccessevent";
+ String RESOURCE_ADMIN_EVENT_TYPE = "resourceadminevent";
+ String DISTRIBUTION_DOWNLOAD_EVENT_TYPE = "distributiondownloadevent";
- public static final String DISTRIBUTION_ENGINE_EVENT_TYPE = "distributionengineevent";
- public static final String DISTRIBUTION_NOTIFICATION_EVENT_TYPE = "distributionnotificationevent";
- public static final String DISTRIBUTION_STATUS_EVENT_TYPE = "distributionstatusevent";
- public static final String DISTRIBUTION_DEPLOY_EVENT_TYPE = "distributiondeployevent";
- public static final String DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE = "auditinggetuebclusterevent";
- public static final String DISTRIBUTION_GET_VALID_ARTIFACT_TYPES_EVENT_TYPE = "auditinggetvalidartifacttypesevent";
+ String DISTRIBUTION_ENGINE_EVENT_TYPE = "distributionengineevent";
+ String DISTRIBUTION_NOTIFICATION_EVENT_TYPE = "distributionnotificationevent";
+ String DISTRIBUTION_STATUS_EVENT_TYPE = "distributionstatusevent";
+ String DISTRIBUTION_DEPLOY_EVENT_TYPE = "distributiondeployevent";
+ String DISTRIBUTION_GET_UEB_CLUSTER_EVENT_TYPE = "auditinggetuebclusterevent";
+ String DISTRIBUTION_GET_VALID_ARTIFACT_TYPES_EVENT_TYPE = "auditinggetvalidartifacttypesevent";
- public static final String AUTH_EVENT_TYPE = "authevent";
- public static final String CONSUMER_EVENT_TYPE = "consumerevent";
- public static final String CATEGORY_EVENT_TYPE = "categoryevent";
- public static final String GET_USERS_LIST_EVENT_TYPE = "getuserslistevent";
- public static final String GET_CATEGORY_HIERARCHY_EVENT_TYPE = "getcategoryhierarchyevent";
- public static final String EXTERNAL_API_EVENT_TYPE = "externalapievent";
+ String AUTH_EVENT_TYPE = "authevent";
+ String CONSUMER_EVENT_TYPE = "consumerevent";
+ String CATEGORY_EVENT_TYPE = "categoryevent";
+ String GET_USERS_LIST_EVENT_TYPE = "getuserslistevent";
+ String GET_CATEGORY_HIERARCHY_EVENT_TYPE = "getcategoryhierarchyevent";
+ String EXTERNAL_API_EVENT_TYPE = "externalapievent";
}
diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java
index b7fce8d912..4ef7c4974e 100644
--- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java
+++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/HealthCheckService.java
@@ -199,9 +199,10 @@ public class HealthCheckService {
healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.FE, HealthCheckStatus.UP,
ExternalConfiguration.getAppVersion(), "OK"));
healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.BE, HealthCheckStatus.DOWN, null, null));
- healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ES, HealthCheckStatus.UNKNOWN, null, null));
healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.TITAN, HealthCheckStatus.UNKNOWN, null, null));
+ healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.CASSANDRA, HealthCheckStatus.UNKNOWN, null, null));
healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.DE, HealthCheckStatus.UNKNOWN, null, null));
+ healthCheckInfos.add(new HealthCheckInfo(HealthCheckComponent.ON_BOARDING, HealthCheckStatus.UNKNOWN, null, null));
HealthCheckWrapper hcWrapper = new HealthCheckWrapper(healthCheckInfos, "UNKNOWN", "UNKNOWN");
return hcWrapper;
}
diff --git a/catalog-model/pom.xml b/catalog-model/pom.xml
index a4538fd3db..ef485ae870 100644
--- a/catalog-model/pom.xml
+++ b/catalog-model/pom.xml
@@ -224,7 +224,19 @@
<version>${commons-jci-core.version}</version>
<scope>test</scope>
</dependency>
- </dependencies>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-module-junit4</artifactId>
+ <version>1.7.0RC4</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-api-mockito-common</artifactId>
+ <version>1.6.5</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
<build>
<plugins>
<plugin>
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java
index 036108e81f..9ffefa6384 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java
@@ -22,9 +22,12 @@ package org.openecomp.sdc.be.model;
import java.io.Serializable;
import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.Optional;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.openecomp.sdc.be.config.ConfigurationManager;
@@ -288,6 +291,13 @@ public abstract class Component implements Serializable {
this.deploymentArtifacts = deploymentArtifacts;
}
+ public Map<String, ArtifactDefinition> getAllArtifacts() {
+ HashMap<String, ArtifactDefinition> allArtifacts = new HashMap<>();
+ allArtifacts.putAll(Optional.ofNullable(this.deploymentArtifacts).orElse(Collections.emptyMap()));
+ allArtifacts.putAll(Optional.ofNullable(this.artifacts).orElse(Collections.emptyMap()));
+ return allArtifacts;
+ }
+
public List<CategoryDefinition> getCategories() {
return categories;
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java
index abcac352cc..1ffbede599 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java
@@ -25,7 +25,7 @@ import java.util.List;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
-public class ComponentInstanceInput extends InputDefinition implements IComponentInstanceConnectedElement {
+public class ComponentInstanceInput extends InputDefinition implements IComponentInstanceConnectedElement, IPropertyInputCommon {
/**
*
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java
index 25bbb50da4..26c5c02ed5 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java
@@ -26,8 +26,7 @@ import java.util.List;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
-
-public class ComponentInstanceProperty extends PropertyDefinition implements IComponentInstanceConnectedElement, Serializable{
+public class ComponentInstanceProperty extends PropertyDefinition implements IComponentInstanceConnectedElement, IPropertyInputCommon, Serializable {
/**
*
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java
index 167fa2f0a1..625afe4f96 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java
@@ -80,4 +80,12 @@ public class GroupDefinition extends GroupDataDefinition implements Serializable
}
+ //returns true iff groupName has the same prefix has the resource
+ public boolean isSamePrefix(String resourceName){
+ String name = this.getName();
+ if ( name != null && name.toLowerCase().trim().startsWith(resourceName.toLowerCase()))
+ return true;
+ return false;
+ }
+
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IPropertyInputCommon.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IPropertyInputCommon.java
new file mode 100644
index 0000000000..2f7a580bb6
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IPropertyInputCommon.java
@@ -0,0 +1,14 @@
+package org.openecomp.sdc.be.model;
+
+import java.util.List;
+
+import org.openecomp.sdc.be.datatypes.elements.PropertyRule;
+import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
+
+public interface IPropertyInputCommon {
+
+ String getType();
+ SchemaDefinition getSchema();
+ List<PropertyRule> getRules();
+ String getName();
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ImportCsarInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ImportCsarInfo.java
new file mode 100644
index 0000000000..460a107c89
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ImportCsarInfo.java
@@ -0,0 +1,73 @@
+package org.openecomp.sdc.be.model;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.PriorityQueue;
+import java.util.Queue;
+
+public class ImportCsarInfo {
+ String vfResourceName;
+ User modifier;
+ String csarUUID;
+ Map<String, byte[]> csar;
+ Map<String, String> createdNodesToscaResourceNames;
+ Queue<String> cvfcToCreateQueue;
+
+ public ImportCsarInfo(String vfResourceName, User modifier, String csarUUID, Map<String, byte[]> csar){
+ this.vfResourceName = vfResourceName;
+ this.modifier = modifier;
+ this.csarUUID = csarUUID;
+ this.csar = csar;
+ this.createdNodesToscaResourceNames = new HashMap<>();
+ this.cvfcToCreateQueue = new PriorityQueue<>();
+ }
+
+ public String getVfResourceName() {
+ return vfResourceName;
+ }
+
+ public void setVfResourceName(String vfResourceName) {
+ this.vfResourceName = vfResourceName;
+ }
+
+ public User getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(User modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getCsarUUID() {
+ return csarUUID;
+ }
+
+ public void setCsarUUID(String csarUUID) {
+ this.csarUUID = csarUUID;
+ }
+
+ public Map<String, byte[]> getCsar() {
+ return csar;
+ }
+
+ public void setCsar(Map<String, byte[]> csar) {
+ this.csar = csar;
+ }
+
+ public Map<String, String> getCreatedNodesToscaResourceNames() {
+ return createdNodesToscaResourceNames;
+ }
+
+ public void setCreatedNodesToscaResourceNames(Map<String, String> createdNodesToscaResourceNames) {
+ this.createdNodesToscaResourceNames = createdNodesToscaResourceNames;
+ }
+
+ public Queue<String> getCvfcToCreateQueue() {
+ return cvfcToCreateQueue;
+ }
+
+ public void setCvfcToCreateQueue(Queue<String> cvfcToCreateQueue) {
+ this.cvfcToCreateQueue = cvfcToCreateQueue;
+ }
+
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java
new file mode 100644
index 0000000000..1da3b8de1c
--- /dev/null
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java
@@ -0,0 +1,55 @@
+package org.openecomp.sdc.be.model;
+
+import java.util.List;
+import java.util.Map;
+
+public class NodeTypeInfo {
+ String type;
+ String templateFileName;
+ List<String> derivedFrom;
+ boolean isNested;
+ Map<String, Object> mappedToscaTemplate;
+
+ public NodeTypeInfo getUnmarkedCopy(){
+ NodeTypeInfo unmarked = new NodeTypeInfo();
+ unmarked.type = this.type;
+ unmarked.templateFileName = this.templateFileName;
+ unmarked.derivedFrom = this.derivedFrom;
+ unmarked.isNested = false;
+ unmarked.mappedToscaTemplate = this.mappedToscaTemplate;
+ return unmarked;
+ }
+
+ public String getType() {
+ return type;
+ }
+ public void setType(String type) {
+ this.type = type;
+ }
+ public String getTemplateFileName() {
+ return templateFileName;
+ }
+ public void setTemplateFileName(String templateFileName) {
+ this.templateFileName = templateFileName;
+ }
+ public List<String> getDerivedFrom() {
+ return derivedFrom;
+ }
+ public void setDerivedFrom(List<String> derivedFrom) {
+ this.derivedFrom = derivedFrom;
+ }
+ public boolean isNested() {
+ return isNested;
+ }
+ public void setNested(boolean isNested) {
+ this.isNested = isNested;
+ }
+
+ public Map<String, Object> getMappedToscaTemplate() {
+ return mappedToscaTemplate;
+ }
+
+ public void setMappedToscaTemplate(Map<String, Object> mappedToscaTemplate) {
+ this.mappedToscaTemplate = mappedToscaTemplate;
+ }
+}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java
index afb013d29a..a3e4f48c51 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java
@@ -146,7 +146,7 @@ public class RequirementAndRelationshipPair implements Serializable {
if ( !savedRelation.getRequirementId().equals(this.getRequirementUid()) ){
return false;
}
- if ( !savedRelation.getCapabiltyId().equals(this.getCapabilityUid()) ){
+ if ( !savedRelation.getCapabilityId().equals(this.getCapabilityUid()) ){
return false;
}
if ( !savedRelation.getRequirement().equals(this.getRequirement()) ){
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java
index a9c6b44324..45fc5f62b3 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java
@@ -255,6 +255,11 @@ public class Resource extends Component implements Serializable {
((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
.setVendorRelease(vendorRelease);
}
+
+ public void setResourceVendorModelNumber(String resourceVendorModelNumber){
+ ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).
+ setResourceVendorModelNumber(resourceVendorModelNumber);
+ }
public String getVendorName() {
return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
@@ -266,6 +271,11 @@ public class Resource extends Component implements Serializable {
.getVendorRelease();
}
+ public String getResourceVendorModelNumber(){
+ return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition())
+ .getResourceVendorModelNumber();
+ }
+
@Override
public String fetchGenericTypeToscaNameFromConfig(){
String result = super.fetchGenericTypeToscaNameFromConfig();
@@ -282,7 +292,7 @@ public class Resource extends Component implements Serializable {
@Override
public boolean shouldGenerateInputs(){
//TODO add complex VFC condition when supported
- return ResourceTypeEnum.VF == this.getResourceType();
+ return ResourceTypeEnum.VF == this.getResourceType() || ResourceTypeEnum.CVFC == this.getResourceType() || ResourceTypeEnum.PNF == this.getResourceType();
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java
index 37a42bd581..cdd171184c 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java
@@ -85,10 +85,26 @@ public class Service extends Component {
public void setNamingPolicy(String namingPolicy) {
getServiceMetadataDefinition().setNamingPolicy(namingPolicy);
}
-
+
public String getNamingPolicy() {
return getServiceMetadataDefinition().getNamingPolicy();
}
+
+ public void setServiceType(String serviceType){
+ getServiceMetadataDefinition().setServiceType(serviceType);
+ }
+
+ public String getServiceType(){
+ return getServiceMetadataDefinition().getServiceType();
+ }
+
+ public void setServiceRole(String serviceRole){
+ getServiceMetadataDefinition().setServiceRole(serviceRole);
+ }
+
+ public String getServiceRole(){
+ return getServiceMetadataDefinition().getServiceRole();
+ }
private ServiceMetadataDataDefinition getServiceMetadataDefinition() {
return (ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition();
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfo.java
index 329e816ea7..eb707787c0 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfo.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadComponentInstanceInfo.java
@@ -29,6 +29,8 @@ public class UploadComponentInstanceInfo {
private Map<String, List<UploadCapInfo>> capabilities;
private Map<String, List<UploadReqInfo>> requirements;
private Map<String, List<UploadPropInfo>> properties;
+ private Map<String, String> capabilitiesNamesToUpdate;
+ private Map<String, String> requirementsNamesToUpdate;
public Map<String, List<UploadPropInfo>> getProperties() {
return properties;
@@ -70,4 +72,20 @@ public class UploadComponentInstanceInfo {
this.requirements = requirements;
}
+ public Map<String, String> getCapabilitiesNamesToUpdate() {
+ return capabilitiesNamesToUpdate;
+ }
+
+ public void setCapabilitiesNamesToUpdate(Map<String, String> capabilitiesNamesToUpdate) {
+ this.capabilitiesNamesToUpdate = capabilitiesNamesToUpdate;
+ }
+
+ public Map<String, String> getRequirementsNamesToUpdate() {
+ return requirementsNamesToUpdate;
+ }
+
+ public void setRequirementsNamesToUpdate(Map<String, String> requirementsNamesToUpdate) {
+ this.requirementsNamesToUpdate = requirementsNamesToUpdate;
+ }
+
}
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 e2766b1092..b8d8cb39de 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
@@ -181,6 +181,27 @@ public class ArtifactsOperations extends BaseOperation {
return Either.left(resMap);
}
+ /**
+ *
+ * @param parentId the id of the instance container
+ * @param instanceId the id of the instance of which to return its artifacts
+ * @return instance and instance deployment artifacts mapped by artifact label name
+ */
+ public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getAllInstanceArtifacts(String parentId, String instanceId) {
+ Map<String, ArtifactDataDefinition> resMap = new HashMap<>();
+ Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> instArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ if (instArtifacts.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(instArtifacts.right().value()));
+ }
+ Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> deployInstArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ if (deployInstArtifacts.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deployInstArtifacts.right().value()));
+ }
+ resMap.putAll(instArtifacts.left().value());
+ resMap.putAll(deployInstArtifacts.left().value());
+ return Either.left(convertArtifactMapToArtifactDefinitionMap(resMap));
+ }
+
public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId) {
Either<Map<String, ArtifactDefinition>, TitanOperationStatus> foundArtifact = null;
@@ -384,36 +405,36 @@ public class ArtifactsOperations extends BaseOperation {
}
private Either<Map<String, ArtifactDefinition>, TitanOperationStatus> getArtifactByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) {
+ Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> artifactsEither = getArtifactsDataByLabel(parentId, instanceId, edgeLabelEnum);
+ if (artifactsEither.isRight()) {
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, artifactsEither.right().value());
+ return Either.right(artifactsEither.right().value());
+ }
+ Map<String, ArtifactDataDefinition> artifactDataMap = artifactsEither.left().value();
+ return Either.left(convertArtifactMapToArtifactDefinitionMap(artifactDataMap));
+ }
- Map<String, ArtifactDefinition> artMap = null;
- Map<String, ArtifactDataDefinition> artifactDataMap = null;
+ private Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> getArtifactsDataByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) {
+ return edgeLabelEnum.isInstanceArtifactsLabel() ? getInstanceArtifactsByLabel(parentId, instanceId, edgeLabelEnum) : getDataFromGraph(parentId, edgeLabelEnum);
+ }
- if (edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) {
- Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum);
- if (resultEither.isRight()) {
- log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value());
- return Either.right(resultEither.right().value());
- }
- artifactDataMap = resultEither.left().value();
- } else {
- Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum);
- if (resultEither.isRight()) {
- log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value());
- return Either.right(resultEither.right().value());
- }
- Map<String, MapArtifactDataDefinition> mapArtifacts = resultEither.left().value();
- MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId);
- if (artifactPerInstance != null) {
- artifactDataMap = artifactPerInstance.getMapToscaDataDefinition();
- }
- }
+ private Map<String, ArtifactDefinition> convertArtifactMapToArtifactDefinitionMap(Map<String, ArtifactDataDefinition> artifactDataMap) {
+ Map<String, ArtifactDefinition> artMap = new HashMap<>();
if (artifactDataMap != null && !artifactDataMap.isEmpty()) {
- artMap = artifactDataMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue())));
- } else {
- artMap = new HashMap<>();
+ artMap = artifactDataMap.entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue())));
}
- return Either.left(artMap);
+ return artMap;
+ }
+ private Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> getInstanceArtifactsByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) {
+ Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum);
+ if (resultEither.isRight()) {
+ log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value());
+ return Either.right(resultEither.right().value());
+ }
+ Map<String, MapArtifactDataDefinition> mapArtifacts = resultEither.left().value();
+ MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId);
+ return artifactPerInstance != null ? Either.left(artifactPerInstance.getMapToscaDataDefinition()) : Either.left(new HashMap<>());
}
private Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> getEdgeLabelEnumFromArtifactGroupType(ArtifactGroupTypeEnum groupType, NodeTypeEnum nodeType) {
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 69ac568ee9..0b60a07a28 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
@@ -1081,12 +1081,10 @@ public abstract class BaseOperation {
*
* @param toscaElementUid
* @param edgeLabel
- * @param vertexLabel
* @param uniqueKeys
- * @param mapKeyField
* @return
*/
- public StorageOperationStatus deleteToscaDataElements(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<String> uniqueKeys, JsonPresentationFields mapKeyField) {
+ public StorageOperationStatus deleteToscaDataElements(String toscaElementUid, EdgeLabelEnum edgeLabel, List<String> uniqueKeys) {
StorageOperationStatus statusRes = StorageOperationStatus.OK;
Either<GraphVertex, TitanOperationStatus> getToscaElementRes;
@@ -1098,7 +1096,7 @@ public abstract class BaseOperation {
statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
}
if (statusRes == StorageOperationStatus.OK) {
- statusRes = deleteToscaDataElements(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKeys, mapKeyField);
+ statusRes = deleteToscaDataElements(getToscaElementRes.left().value(), edgeLabel, uniqueKeys);
}
return statusRes;
}
@@ -1219,25 +1217,22 @@ public abstract class BaseOperation {
List<String> uniqueKeys = new ArrayList<>();
uniqueKeys.add(uniqueKey);
- return deleteToscaDataElements(toscaElement, edgeLabel, vertexLabel, uniqueKeys, mapKeyField);
+ return deleteToscaDataElements(toscaElement, edgeLabel, uniqueKeys);
}
@SuppressWarnings("unchecked")
- /**
- * Deletes tosca data elements belonging to tosca element according label
- *
- * @param toscaElement
- * @param edgeLabel
- * @param vertexLabel
- * @param uniqueKeys
- * @param mapKeyField
- * @return
- */
- public StorageOperationStatus deleteToscaDataElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<String> uniqueKeys, JsonPresentationFields mapKeyField) {
+/**
+ * Deletes tosca data elements belonging to tosca element according label
+ * @param toscaElement
+ * @param edgeLabel
+ * @param uniqueKeys
+ * @return
+ */
+ public StorageOperationStatus deleteToscaDataElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List<String> uniqueKeys) {
StorageOperationStatus result = null;
GraphVertex toscaDataVertex;
- Map<String, ToscaDataDefinition> existingToscaDataMap = null;
+ Map<String, ToscaDataDefinition> existingToscaDataMap;
Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson);
if (toscaDataVertexRes.isRight()) {
TitanOperationStatus status = toscaDataVertexRes.right().value();
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 737c1c2d40..5f7502e7ce 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
@@ -139,7 +139,7 @@ public class GroupsOperation extends BaseOperation {
}
if (result == null) {
List<String> groupName = groups.stream().map(g -> g.getName()).collect(Collectors.toList());
- status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupName, JsonPresentationFields.NAME);
+ status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.GROUPS, groupName);
if (status != StorageOperationStatus.OK) {
result = Either.right(status);
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 33db64234b..66d26c748f 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
@@ -37,8 +37,6 @@ import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
-import org.apache.tinkerpop.gremlin.structure.Direction;
-import org.apache.tinkerpop.gremlin.structure.Edge;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
@@ -67,12 +65,10 @@ import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.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.DistributionStatusEnum;
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.model.RelationshipImpl;
@@ -849,10 +845,8 @@ public class NodeTemplateOperation extends BaseOperation {
dataDefinition.setComponentVersion((String) originToscaElement.getMetadataValue(JsonPresentationFields.VERSION));
if (StringUtils.isEmpty(dataDefinition.getComponentName()) && originToscaElement != null)
dataDefinition.setComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.NAME));
-// if (StringUtils.isEmpty(dataDefinition.getToscaComponentName()) && originToscaElement != null)
-
- dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
-
+ if (originToscaElement != null)
+ dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
if (dataDefinition.getOriginType() == null && originToscaElement != null) {
ResourceTypeEnum resourceType = originToscaElement.getResourceType();
OriginTypeEnum originType = null;
@@ -863,12 +857,18 @@ public class NodeTemplateOperation extends BaseOperation {
case VFC:
originType = OriginTypeEnum.VFC;
break;
+ case CVFC:
+ originType = OriginTypeEnum.CVFC;
+ break;
case VL:
originType = OriginTypeEnum.VL;
break;
case CP:
originType = OriginTypeEnum.CP;
break;
+ case PNF:
+ originType = OriginTypeEnum.PNF;
+ break;
default:
break;
}
@@ -1016,7 +1016,7 @@ public class NodeTemplateOperation extends BaseOperation {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId, updateElement.right().value());
return DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value());
}
- // update cap/req jsons, fullfilled cap/req jsons!!!!!
+ // update cap/req jsons, fulfilled cap/req jsons!!!!!
Either<GraphVertex, TitanOperationStatus> status;
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update calculated capabilty for container {}", containerV.getUniqueId());
status = updateOrCopyOnUpdate(capResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
@@ -1070,7 +1070,7 @@ public class NodeTemplateOperation extends BaseOperation {
}
GraphVertex containerV = containerVEither.left().value();
- // DE191707 - validatations
+ // DE191707 - validations
Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) containerV.getJson();
CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances();
@@ -1092,16 +1092,15 @@ public class NodeTemplateOperation extends BaseOperation {
Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
-
}
- Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty = capResult.left().value().getRight();
+ Map<String, MapListCapabiltyDataDefinition> calculatedCapability = capResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
}
- Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight();
+ Map<String, MapListCapabiltyDataDefinition> fulfilledCapability = capFullResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
if (reqResult.isRight()) {
@@ -1113,7 +1112,7 @@ public class NodeTemplateOperation extends BaseOperation {
if (reqResult.isRight()) {
return Either.right(reqResult.right().value());
}
- Map<String, MapListRequirementDataDefinition> fullfilledRequirement = reqFullResult.left().value().getRight();
+ Map<String, MapListRequirementDataDefinition> fulfilledRequirement = reqFullResult.left().value().getRight();
for (RequirementAndRelationshipPair relationPair : relationPairList) {
Iterator<Entry<String, RelationshipInstDataDefinition>> iterator = relations.entrySet().iterator();
@@ -1123,16 +1122,16 @@ public class NodeTemplateOperation extends BaseOperation {
RelationshipInstDataDefinition relationInJson = entryInJson.getValue();
if (relationInJson.getFromId().equals(fromResInstanceUid) && relationInJson.getToId().equals(toResInstanceUid)) {
if (relationPair.equalsTo(relationInJson)) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Remove relation from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(),
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Remove relation from {} to {} capability {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(),
relationInJson.getCapabilityOwnerId(), relationInJson.getRequirementOwnerId());
iterator.remove();
// update calculated cap/req
- StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relationInJson);
+ StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapability, fulfilledCapability, toResInstanceUid, relationInJson);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
- status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, fromResInstanceUid, relationInJson);
+ status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fulfilledRequirement, fromResInstanceUid, relationInJson);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
@@ -1168,90 +1167,87 @@ public class NodeTemplateOperation extends BaseOperation {
private StorageOperationStatus updateCalculatedRequirementsAfterDeleteRelation(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid,
RelationshipInstDataDefinition relation) {
StorageOperationStatus status;
+ String hereIsTheKey = null;
MapListRequirementDataDefinition reqByInstance = calculatedRequirement.get(fromResInstanceUid);
- if (reqByInstance == null) {
- // move from fullfilled
- status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation);
+ if (reqByInstance == null || reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()) == null) {
+ // move from fulfilled
+ status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey);
} else {
- ListRequirementDataDefinition reqByType = reqByInstance.findByKey(relation.getType());
- if (reqByType == null) {
- // move from fullfilled
- status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation);
- } else {
- Optional<RequirementDataDefinition> requirementOptional = reqByType.getListToscaDataDefinition().stream()
- .filter(cap -> cap.getOwnerId().equals(relation.getRequirementOwnerId()) && cap.getName().equals(relation.getRequirement()) && cap.getUniqueId().equals(relation.getRequirementId())).findFirst();
+ hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId());
+ ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey);
+ Optional<RequirementDataDefinition> requirementOptional = reqByType.getListToscaDataDefinition().stream()
+ .filter(req -> req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())).findFirst();
- if (requirementOptional.isPresent()) {
+ if (requirementOptional.isPresent()) {
- RequirementDataDefinition requirement = requirementOptional.get();
- String leftOccurrences = requirement.getLeftOccurrences();
- if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
- Integer leftIntValue = Integer.parseInt(leftOccurrences);
- ++leftIntValue;
- requirement.setLeftOccurrences(String.valueOf(leftIntValue));
- }
- status = StorageOperationStatus.OK;
- } else {
- // move from fullfilled
- status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation);
+ RequirementDataDefinition requirement = requirementOptional.get();
+ String leftOccurrences = requirement.getLeftOccurrences();
+ if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
+ Integer leftIntValue = Integer.parseInt(leftOccurrences);
+ ++leftIntValue;
+ requirement.setLeftOccurrences(String.valueOf(leftIntValue));
}
+ status = StorageOperationStatus.OK;
+ } else {
+ // move from fulfilled
+ status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey);
}
}
return status;
}
- private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty, String toResInstanceUid,
+
+ private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map<String, MapListCapabiltyDataDefinition> calculatedCapability, Map<String, MapListCapabiltyDataDefinition> fullFilledCapability, String toResInstanceUid,
RelationshipInstDataDefinition relation) {
StorageOperationStatus status;
- MapListCapabiltyDataDefinition capByInstance = calculatedCapabilty.get(toResInstanceUid);
- if (capByInstance == null) {
- // move from fullfilled
- status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation);
+ String hereIsTheKey = null;
+ MapListCapabiltyDataDefinition capByInstance = calculatedCapability.get(toResInstanceUid);
+ if (capByInstance == null || capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()) == null) {
+ // move from fulfilled
+ status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey);
} else {
- ListCapabilityDataDefinition capByType = capByInstance.findByKey(relation.getType());
- if (capByType == null) {
- // move from fullfilled
- status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation);
- } else {
- Optional<CapabilityDataDefinition> capabiltyOptional = capByType.getListToscaDataDefinition().stream()
- .filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabiltyId())).findFirst();
+ hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId());
+ ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey);
+ Optional<CapabilityDataDefinition> capabilityOptional = capByType.getListToscaDataDefinition().stream()
+ .filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())).findFirst();
- if (capabiltyOptional.isPresent()) {
+ if (capabilityOptional.isPresent()) {
- CapabilityDataDefinition capability = capabiltyOptional.get();
- String leftOccurrences = capability.getLeftOccurrences();
- if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
- Integer leftIntValue = Integer.parseInt(leftOccurrences);
- ++leftIntValue;
- capability.setLeftOccurrences(String.valueOf(leftIntValue));
- }
- status = StorageOperationStatus.OK;
- } else {
- // move from fullfilled
- status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation);
+ CapabilityDataDefinition capability = capabilityOptional.get();
+ String leftOccurrences = capability.getLeftOccurrences();
+ if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
+ Integer leftIntValue = Integer.parseInt(leftOccurrences);
+ ++leftIntValue;
+ capability.setLeftOccurrences(String.valueOf(leftIntValue));
}
+ status = StorageOperationStatus.OK;
+ } else {
+ // move from fulfilled
+ status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey);
}
}
return status;
}
- private StorageOperationStatus moveFromFullFilledCapabilty(Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty, String toResInstanceUid,
- RelationshipInstDataDefinition relation) {
- MapListCapabiltyDataDefinition capByInstance = fullFilledCapabilty.get(toResInstanceUid);
+ private StorageOperationStatus moveFromFullFilledCapabilty(Map<String, MapListCapabiltyDataDefinition> calculatedCapability, Map<String, MapListCapabiltyDataDefinition> fullFilledCapability, String toResInstanceUid,
+ RelationshipInstDataDefinition relation, String hereIsTheKey) {
+ MapListCapabiltyDataDefinition capByInstance = fullFilledCapability.get(toResInstanceUid);
if (capByInstance == null) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty in fullfilled list for instance {} ", toResInstanceUid);
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capability in fulfilled list for instance {} ", toResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
- ListCapabilityDataDefinition capByType = capByInstance.findByKey(relation.getType());
- if (capByType == null) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty type {} in fullfilled list for instance {} ", relation.getType(), toResInstanceUid);
+ if (null == hereIsTheKey)
+ hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId());
+ if (null == hereIsTheKey) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capability with id {} in fulfilled list for instance {} ", relation.getCapabilityId(), toResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
+ ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey);
Iterator<CapabilityDataDefinition> iterator = capByType.getListToscaDataDefinition().iterator();
boolean found = false;
while (iterator.hasNext()) {
CapabilityDataDefinition cap = iterator.next();
- if (cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getName().equals(relation.getRequirement()) && cap.getUniqueId().equals(relation.getCapabiltyId())) {
+ if (cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())) {
found = true;
iterator.remove();
// return to calculated list
@@ -1260,38 +1256,40 @@ public class NodeTemplateOperation extends BaseOperation {
++leftIntValue;
cap.setLeftOccurrences(String.valueOf(leftIntValue));
- MapListCapabiltyDataDefinition mapListCapaDataDef = calculatedCapabilty.get(toResInstanceUid);
+ MapListCapabiltyDataDefinition mapListCapaDataDef = calculatedCapability.get(toResInstanceUid);
if (mapListCapaDataDef == null) {
mapListCapaDataDef = new MapListCapabiltyDataDefinition();
}
- ListCapabilityDataDefinition findByKey = mapListCapaDataDef.findByKey(relation.getType());
+ ListCapabilityDataDefinition findByKey = mapListCapaDataDef.findByKey(hereIsTheKey);
if (findByKey == null) {
findByKey = new ListCapabilityDataDefinition();
- mapListCapaDataDef.put(relation.getType(), findByKey);
+ mapListCapaDataDef.put(hereIsTheKey, findByKey);
}
findByKey.add(cap);
break;
}
}
if (found == false) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty type {} with ownerId {} in fullfilled list for instance {} ", relation.getType(), relation.getCapabilityOwnerId(), toResInstanceUid);
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capability type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getCapabilityOwnerId(), toResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
return StorageOperationStatus.OK;
}
private StorageOperationStatus moveFromFullFilledRequirement(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid,
- RelationshipInstDataDefinition relation) {
+ RelationshipInstDataDefinition relation, String hereIsTheKey) {
MapListRequirementDataDefinition reqByInstance = fullFilledRequirement.get(fromResInstanceUid);
if (reqByInstance == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement in fullfilled list for instance {} ", fromResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
- ListRequirementDataDefinition reqByType = reqByInstance.findByKey(relation.getType());
- if (reqByType == null) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} in fullfilled list for instance {} ", relation.getType(), fromResInstanceUid);
+ if(null == hereIsTheKey)
+ hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId());
+ if (null == hereIsTheKey) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement with id {} in fulfilled list for instance {} ", relation.getRequirementId(), fromResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
+ ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey);
Iterator<RequirementDataDefinition> iterator = reqByType.getListToscaDataDefinition().iterator();
boolean found = false;
while (iterator.hasNext()) {
@@ -1309,17 +1307,17 @@ public class NodeTemplateOperation extends BaseOperation {
if (mapListReqDataDef == null) {
mapListReqDataDef = new MapListRequirementDataDefinition();
}
- ListRequirementDataDefinition findByKey = mapListReqDataDef.findByKey(relation.getType());
+ ListRequirementDataDefinition findByKey = mapListReqDataDef.findByKey(hereIsTheKey);
if (findByKey == null) {
findByKey = new ListRequirementDataDefinition();
- mapListReqDataDef.put(relation.getType(), findByKey);
+ mapListReqDataDef.put(hereIsTheKey, findByKey);
}
findByKey.add(req);
break;
}
}
if (found == false) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fullfilled list for instance {} ", relation.getType(), relation.getCapabilityOwnerId(), fromResInstanceUid);
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getRequirementOwnerId(), fromResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
return StorageOperationStatus.OK;
@@ -1414,22 +1412,22 @@ public class NodeTemplateOperation extends BaseOperation {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for type {} for instance {} in container {}.", type, toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
- CapabilityDataDefinition capabiltyForRelation = null;
+ CapabilityDataDefinition capabilityForRelation = null;
Iterator<CapabilityDataDefinition> iteratorCap = listCapabilityDataDefinition.getListToscaDataDefinition().iterator();
while (iteratorCap.hasNext()) {
CapabilityDataDefinition cap = iteratorCap.next();
if (cap.getUniqueId().equals(relationPair.getCapabilityUid()) && cap.getOwnerId().equals(relationPair.getCapabilityOwnerId())) {
- capabiltyForRelation = cap;
+ capabilityForRelation = cap;
String leftOccurrences = cap.getLeftOccurrences();
if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
Integer leftIntValue = Integer.parseInt(leftOccurrences);
if (leftIntValue > 0) {
--leftIntValue;
- capabiltyForRelation.setLeftOccurrences(String.valueOf(leftIntValue));
+ capabilityForRelation.setLeftOccurrences(String.valueOf(leftIntValue));
if (leftIntValue == 0) {
// remove from calculated
iteratorCap.remove();
- // move to fullfilled
+ // move to fulfilled
MapListCapabiltyDataDefinition mapListCapabiltyFullFilledInst = fullfilledCapabilty.get(toInstId);
if (mapListCapabiltyFullFilledInst == null) {
mapListCapabiltyFullFilledInst = new MapListCapabiltyDataDefinition();
@@ -1441,17 +1439,17 @@ public class NodeTemplateOperation extends BaseOperation {
listCapabilityFull = new ListCapabilityDataDefinition();
mapListCapabiltyFullFilledInst.put(type, listCapabilityFull);
}
- listCapabilityFull.add(capabiltyForRelation);
+ listCapabilityFull.add(capabilityForRelation);
}
break;
} else {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabiltyForRelation.getType(), toInstId, containerId);
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabilityForRelation.getType(), toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
}
}
}
- if (capabiltyForRelation == null) {
+ if (capabilityForRelation == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch capabilty for type {} for instance {} in container {}.", type, toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
@@ -1485,7 +1483,7 @@ public class NodeTemplateOperation extends BaseOperation {
if (leftIntValue == 0) {
// remove from calculated
iteratorReq.remove();
- // move to fullfilled
+ // move to fulfilled
MapListRequirementDataDefinition mapListRequirementFullFilledInst = fullfilledRequirement.get(fromInstId);
if (mapListRequirementFullFilledInst == null) {
mapListRequirementFullFilledInst = new MapListRequirementDataDefinition();
@@ -1507,16 +1505,14 @@ public class NodeTemplateOperation extends BaseOperation {
}
}
}
- if (!capabiltyForRelation.getType().equals(requirementForRelation.getCapability())) {
- CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No math for capabilty from type {} and requirement {} from {} to {} in container {}.", capabiltyForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId,
+ if (!capabilityForRelation.getType().equals(requirementForRelation.getCapability())) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No math for capability from type {} and requirement {} from {} to {} in container {}.", capabilityForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId,
containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
RelationshipInstDataDefinition relationshipTypeData = buildRelationshipInstData(fromInstId, toInstId, relationPair);
-
relationshipTypeData.setType(requirementForRelation.getRelationship());
-
return Either.left(relationshipTypeData);
}
@@ -1531,7 +1527,7 @@ public class NodeTemplateOperation extends BaseOperation {
relationshipInstData.setModificationTime(creationDate);
relationshipInstData.setCapabilityOwnerId(relationPair.getCapabilityOwnerId());
relationshipInstData.setRequirementOwnerId(relationPair.getRequirementOwnerId());
- relationshipInstData.setCapabiltyId(relationPair.getCapabilityUid());
+ relationshipInstData.setCapabilityId(relationPair.getCapabilityUid());
relationshipInstData.setRequirementId(relationPair.getRequirementUid());
relationshipInstData.setFromId(fromResInstanceUid);
relationshipInstData.setToId(toInstId);
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 99a602f234..2d160bfc82 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
@@ -140,7 +140,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
return result;
}
StorageOperationStatus associateInstGroups = associateInstGroupsToComponent(topologyTemplateVertex, topologyTemplate);
- if (associateInstProperties != StorageOperationStatus.OK) {
+ if (associateInstGroups != StorageOperationStatus.OK) {
result = Either.right(associateInstInputs);
return result;
}
@@ -786,12 +786,11 @@ public class TopologyTemplateOperation extends ToscaElementOperation {
GraphVertex categoryV = childVertex.left().value();
Map<GraphPropertyEnum, Object> metadataProperties = categoryV.getMetadataProperties();
CategoryDefinition category = new CategoryDefinition();
- category.setUniqueId((String) metadataProperties.get(GraphPropertyEnum.UNIQUE_ID));
+ category.setUniqueId(categoryV.getUniqueId());
category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME));
category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME));
- Type listTypeCat = new TypeToken<List<String>>() {
- }.getType();
+ Type listTypeCat = new TypeToken<List<String>>() {}.getType();
List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS.getProperty()), listTypeCat);
category.setIcons(iconsfromJsonCat);
categories.add(category);
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 d57e7cc255..4282a2cba8 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
@@ -27,7 +27,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
@@ -37,9 +36,7 @@ import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
-
import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum;
@@ -55,20 +52,16 @@ import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
-import org.openecomp.sdc.be.model.ArtifactDefinition;
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.LifecycleStateEnum;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
@@ -78,10 +71,8 @@ import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
-import org.openecomp.sdc.exception.ResponseFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -1014,8 +1005,8 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
//TODO remove after jsonModelMigration
- public void resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) {
- fixToscaComponentName(vfInst, origCompMap);
+ public boolean resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) {
+ return fixToscaComponentName(vfInst, origCompMap);
}
private boolean fixToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) {
@@ -1035,7 +1026,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value());
return false;
}
- origComp = origCompEither.left().value();
+ origComp = origCompEither.left().value();
origCompMap.put(origCompUid, origComp);
} else {
origComp = origCompMap.get(origCompUid);
@@ -1460,4 +1451,72 @@ public class ToscaElementLifecycleOperation extends BaseOperation {
}
return false;
}
+
+ public Either<ToscaElement,StorageOperationStatus> forceCerificationOfToscaElement(String toscaElementId, String modifierId, String ownerId) {
+ Either<GraphVertex, StorageOperationStatus> resultUpdate = null;
+ Either<ToscaElement, StorageOperationStatus> result = null;
+ GraphVertex toscaElement = null;
+ GraphVertex modifier = null;
+ GraphVertex owner;
+ try {
+ Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId));
+ if (getVerticesRes.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value()));
+ }
+ if (result == null) {
+ toscaElement = getVerticesRes.left().value().get(toscaElementId);
+ modifier = getVerticesRes.left().value().get(modifierId);
+ owner = getVerticesRes.left().value().get(ownerId);
+
+ StorageOperationStatus status = handleRelationsUponForceCertification(toscaElement, modifier, owner);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status);
+ }
+ }
+ if (result == null) {
+ LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFIED;
+
+ toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ toscaElement.addMetadataProperty(GraphPropertyEnum.VERSION, "1.0");
+
+ resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement);
+ if (resultUpdate.isRight()) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value());
+ result = Either.right(resultUpdate.right().value());
+ }
+ }
+ if (result == null) {
+ ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel());
+ result = operation.getToscaElement(toscaElement.getUniqueId());
+ }
+ return result;
+
+ } catch (Exception e) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage());
+ }
+ return result;
+ }
+
+ private StorageOperationStatus handleRelationsUponForceCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) {
+
+ StorageOperationStatus result = null;
+ TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE);
+ if (status != TitanOperationStatus.OK) {
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (result == null) {
+ Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class);
+ properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFIED);
+ status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties);
+ if (status != TitanOperationStatus.OK) {
+ CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status);
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ }
+ 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 99cbd34c9b..5aceb2ffd2 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
@@ -20,16 +20,9 @@
package org.openecomp.sdc.be.model.jsontitan.operations;
-import java.lang.reflect.Type;
-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 com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import fj.data.Either;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
@@ -59,7 +52,6 @@ import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
-import org.openecomp.sdc.be.resources.data.UserData;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
import org.openecomp.sdc.common.util.ValidationUtils;
@@ -67,10 +59,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import com.google.gson.Gson;
-import com.google.gson.reflect.TypeToken;
-
-import fj.data.Either;
+import java.lang.reflect.Type;
+import java.util.*;
+import java.util.Map.Entry;
public abstract class ToscaElementOperation extends BaseOperation {
private static Logger log = LoggerFactory.getLogger(ToscaElementOperation.class.getName());
@@ -1074,13 +1065,15 @@ public abstract class ToscaElementOperation extends BaseOperation {
return status;
}
- public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement, boolean isHighestVersions) {
+ 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, toscaElement);
- } else {
- listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, toscaElement);
+ listOfComponents = getListOfHighestComponents(componentType, excludeTypes);
}
+ else {
+ listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes);
+ }
+
if (listOfComponents.isRight() && listOfComponents.right().value() != TitanOperationStatus.NOT_FOUND) {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfComponents.right().value()));
}
@@ -1091,7 +1084,7 @@ public abstract class ToscaElementOperation extends BaseOperation {
for (GraphVertex vertexComponent : highestAndAllCertified) {
Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true));
if (component.isRight()) {
- log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), component.right().value());
+ log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), component.right().value());
return Either.right(component.right().value());
} else {
result.add(component.left().value());
@@ -1102,82 +1095,55 @@ public abstract class ToscaElementOperation extends BaseOperation {
return Either.left(result);
}
- private Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement) {
+ private Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes) {
Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>();
+ Map<GraphPropertyEnum, Object> propertiesHasNotToMatch = new HashMap<>();
propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
if (componentType == ComponentTypeEnum.RESOURCE) {
propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, false);
+ propertiesHasNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
}
-
- Map<GraphPropertyEnum, Object> propertiesHasNotToMatch = new HashMap<>();
propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
- return titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement), propertiesToMatch, propertiesHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
+ return titanDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, JsonParseFlagEnum.ParseMetadata);
}
- public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType, ToscaElementTypeEnum toscaElement) {
+ // 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);
+
Map<GraphPropertyEnum, Object> propertiesToMatchCertified = new HashMap<>();
+ Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new HashMap<>();
propertiesToMatchCertified.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
propertiesToMatchCertified.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
if (componentType == ComponentTypeEnum.RESOURCE) {
propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false);
+ propertiesHasNotToMatchCertified.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes);
}
- Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new HashMap<>();
propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true);
+ propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- Either<List<GraphVertex>, TitanOperationStatus> certifiedNodes = titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement), propertiesToMatchCertified, propertiesHasNotToMatchCertified,
+ Either<List<GraphVertex>, TitanOperationStatus> certifiedNotHighestNodes = titanDao.getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified,
JsonParseFlagEnum.ParseMetadata);
- if (certifiedNodes.isRight() && certifiedNodes.right().value() != TitanOperationStatus.NOT_FOUND) {
- return Either.right(certifiedNodes.right().value());
- }
-
- Map<GraphPropertyEnum, Object> propertiesToMatchHighest = new HashMap<>();
- propertiesToMatchHighest.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- propertiesToMatchHighest.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
- if (componentType == ComponentTypeEnum.RESOURCE) {
- propertiesToMatchHighest.put(GraphPropertyEnum.IS_ABSTRACT, false);
- }
-
- Map<GraphPropertyEnum, Object> propertiesHasNotToMatchHighest = new HashMap<>();
- propertiesHasNotToMatchHighest.put(GraphPropertyEnum.IS_DELETED, true);
- propertiesHasNotToMatchHighest.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
-
- Either<List<GraphVertex>, TitanOperationStatus> highestNode = titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement), propertiesToMatchHighest, propertiesHasNotToMatchHighest, JsonParseFlagEnum.ParseMetadata);
- if (highestNode.isRight() && highestNode.right().value() != TitanOperationStatus.NOT_FOUND) {
- return Either.right(highestNode.right().value());
+ if (certifiedNotHighestNodes.isRight() && certifiedNotHighestNodes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ return Either.right(certifiedNotHighestNodes.right().value());
}
long endFetchAllStates = System.currentTimeMillis();
List<GraphVertex> allNodes = new ArrayList<>();
- if (certifiedNodes.isLeft()) {
- allNodes.addAll(certifiedNodes.left().value());
- }
- if (highestNode.isLeft()) {
- allNodes.addAll(highestNode.left().value());
- }
-
- int certifiedSize;
- int nonCertifiedSize;
-
- if (certifiedNodes.isRight()) {
- certifiedSize = 0;
- } else {
- certifiedSize = certifiedNodes.left().value().size();
+ if (certifiedNotHighestNodes.isLeft()) {
+ allNodes.addAll(certifiedNotHighestNodes.left().value());
}
-
- if (highestNode.isRight()) {
- nonCertifiedSize = 0;
- } else {
- nonCertifiedSize = highestNode.left().value().size();
+ if (highestNodes.isLeft()) {
+ allNodes.addAll(highestNodes.left().value());
}
- log.debug("Fetch catalog {}s all states: certified {}, noncertified {}", componentType, certifiedSize, nonCertifiedSize);
log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates);
return Either.left(allNodes);
}
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 8999340f0a..64424a8070 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
@@ -21,9 +21,9 @@
package org.openecomp.sdc.be.model.jsontitan.operations;
import java.util.*;
+import fj.data.Either;
import java.util.Map.Entry;
import java.util.stream.Collectors;
-
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
@@ -36,45 +36,11 @@ import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty;
-import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
-import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
-import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
-import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
-import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
-import org.openecomp.sdc.be.datatypes.enums.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.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.DistributionStatusEnum;
-import org.openecomp.sdc.be.model.GroupDefinition;
-import org.openecomp.sdc.be.model.GroupInstance;
-import org.openecomp.sdc.be.model.InputDefinition;
-import org.openecomp.sdc.be.model.LifecycleStateEnum;
-import org.openecomp.sdc.be.model.PropertyDefinition;
-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.Service;
-import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.datatypes.elements.*;
+import org.openecomp.sdc.be.datatypes.enums.*;
+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.datamodel.ToscaElementTypeEnum;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
@@ -88,932 +54,935 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import fj.data.Either;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
@org.springframework.stereotype.Component("tosca-operation-facade")
public class ToscaOperationFacade {
- @Autowired
- private NodeTypeOperation nodeTypeOperation;
- @Autowired
- private TopologyTemplateOperation topologyTemplateOperation;
- @Autowired
- private NodeTemplateOperation nodeTemplateOperation;
- @Autowired
- private GroupsOperation groupsOperation;
- @Autowired
- private TitanDao titanDao;
-
- private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName());
-
- public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
-
- return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
-
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
- ComponentParametersView filters = new ComponentParametersView();
- filters.setIgnoreCapabiltyProperties(false);
-
- return getToscaElement(componentId, filters);
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
-
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag());
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
-
- }
- return getToscaElementByOperation(getVertexEither.left().value(), filters);
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
-
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, parseFlag);
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
-
- }
- return getToscaElementByOperation(getVertexEither.left().value());
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
- return getToscaElementByOperation(componentVertex);
- }
-
- public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
-
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
- if (getVertexEither.isRight()) {
- TitanOperationStatus status = getVertexEither.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- return Either.left(false);
- } else {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
- }
- }
- return Either.left(true);
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
- Map<GraphPropertyEnum, Object> props = new HashMap<>();
- props.put(GraphPropertyEnum.UUID, component.getUUID());
- props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
- props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
- Either<List<GraphVertex>, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props);
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", component.getUniqueId(), getVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
-
- }
- return getToscaElementByOperation(getVertexEither.left().value().get(0));
- }
-
- private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
- return getToscaElementByOperation(componentV, new ComponentParametersView());
- }
-
- private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) {
- VertexTypeEnum label = componentV.getLabel();
-
- ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
- Either<ToscaElement, StorageOperationStatus> toscaElement;
- String componentId = componentV.getUniqueId();
- if (toscaOperation != null) {
- log.debug("Need to fetch tosca element for id {}", componentId);
- toscaElement = toscaOperation.getToscaElement(componentV, filters);
- } else {
- log.debug("not supported tosca type {} for id {}", label, componentId);
- toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
- }
- if (toscaElement.isRight()) {
- return Either.right(toscaElement.right().value());
- }
- return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value()));
- }
-
- private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
- VertexTypeEnum label = componentV.getLabel();
- switch (label) {
- case NODE_TYPE:
- return nodeTypeOperation;
- case TOPOLOGY_TEMPLATE:
- return topologyTemplateOperation;
- default:
- return null;
- }
- }
-
- /**
- *
- * @param resource
- * @return
- */
- public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
- ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
-
- ToscaElementOperation toscaElementOperation = getToscaElementOperation(toscaElement);
- Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
- if (createToscaElement.isLeft()) {
- log.debug("Component created successfully!!!");
- T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
- return Either.left(dataModel);
- }
- return Either.right(createToscaElement.right().value());
- }
-
- /**
- *
- * @param componentToDelete
- * @return
- */
- public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
-
- if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
- // component already marked for delete
- return StorageOperationStatus.OK;
- } else {
-
- Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
- if (getResponse.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentToDelete.getUniqueId(), getResponse.right().value());
- return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value());
-
- }
- GraphVertex componentV = getResponse.left().value();
-
- // same operation for node type and topology template operations
- Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
- if (result.isRight()) {
- return result.right().value();
- }
- return StorageOperationStatus.OK;
- }
- }
-
- /**
- *
- * @param componentId
- * @return
- */
- public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
-
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
-
- }
- Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
- if (deleteElement.isRight()) {
- log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
- return Either.right(deleteElement.right().value());
- }
- T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
-
- return Either.left(dataModel);
- }
-
- private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
- VertexTypeEnum label = componentV.getLabel();
- Either<ToscaElement, StorageOperationStatus> toscaElement;
- Object componentId = componentV.getUniqueId();
- switch (label) {
- case NODE_TYPE:
- log.debug("Need to fetch node type for id {}", componentId);
- toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
- break;
- case TOPOLOGY_TEMPLATE:
- log.debug("Need to fetch topology template for id {}", componentId);
- toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
- break;
- default:
- log.debug("not supported tosca type {} for id {}", label, componentId);
- toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
- break;
- }
- return toscaElement;
- }
-
- private ToscaElementOperation getToscaElementOperation(ToscaElement toscaElement) {
-
- ComponentTypeEnum componentType = toscaElement.getComponentType();
- switch (componentType) {
- case RESOURCE:
- ResourceTypeEnum resourceType = toscaElement.getResourceType();
- if (resourceType == ResourceTypeEnum.VF) {
- return topologyTemplateOperation;
- } else {
- return nodeTypeOperation;
- }
- case SERVICE:
- case PRODUCT:
- return topologyTemplateOperation;
- default:
- break;
- }
- return null;
- }
-
- private ToscaElementOperation getToscaElementOperation(Component component) {
-
- switch (component.getComponentType()) {
- case RESOURCE:
- ResourceTypeEnum resourceType = ((Resource) component).getResourceType();
- if (resourceType != null && resourceType == ResourceTypeEnum.VF) {
- return topologyTemplateOperation;
- } else {
- return nodeTypeOperation;
- }
- case SERVICE:
- case PRODUCT:
- return topologyTemplateOperation;
- default:
- break;
- }
- return null;
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
- return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
-
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
- return getLatestByName(GraphPropertyEnum.NAME, resourceName);
-
- }
-
- public Either<Integer, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) {
- Either<List<ToscaElement>, StorageOperationStatus> byCsar = null;
-
- Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
- properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
-
- Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
-
- if (resources.isRight()) {
- if (resources.right().value() == TitanOperationStatus.NOT_FOUND) {
- return Either.left(new Integer(0));
- } else {
- log.debug("failed to get resources from graph with property name: {}", csarUUID);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
- }
- }
-
- List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
-
- return Either.left(new Integer(resourceList.size()));
-
- }
+ @Autowired
+ private NodeTypeOperation nodeTypeOperation;
+ @Autowired
+ private TopologyTemplateOperation topologyTemplateOperation;
+ @Autowired
+ private NodeTemplateOperation nodeTemplateOperation;
+ @Autowired
+ private GroupsOperation groupsOperation;
+ @Autowired
+ private TitanDao titanDao;
+
+ private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName());
+
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) {
+
+ return getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
+
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) {
+ ComponentParametersView filters = new ComponentParametersView();
+ filters.setIgnoreCapabiltyProperties(false);
+
+ return getToscaElement(componentId, filters);
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag());
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+ return getToscaElementByOperation(getVertexEither.left().value(), filters);
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, parseFlag);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+ return getToscaElementByOperation(getVertexEither.left().value());
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) {
+ return getToscaElementByOperation(componentVertex);
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
+ if (getVertexEither.isRight()) {
+ TitanOperationStatus status = getVertexEither.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ return Either.left(false);
+ } else {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+ }
+ }
+ return Either.left(true);
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) {
+ Map<GraphPropertyEnum, Object> props = new HashMap<>();
+ props.put(GraphPropertyEnum.UUID, component.getUUID());
+ props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", component.getUniqueId(), getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+ return getToscaElementByOperation(getVertexEither.left().value().get(0));
+ }
+
+ private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) {
+ return getToscaElementByOperation(componentV, new ComponentParametersView());
+ }
+
+ private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) {
+ VertexTypeEnum label = componentV.getLabel();
+
+ ToscaElementOperation toscaOperation = getToscaElementOperation(componentV);
+ Either<ToscaElement, StorageOperationStatus> toscaElement;
+ String componentId = componentV.getUniqueId();
+ if (toscaOperation != null) {
+ log.debug("Need to fetch tosca element for id {}", componentId);
+ toscaElement = toscaOperation.getToscaElement(componentV, filters);
+ } else {
+ log.debug("not supported tosca type {} for id {}", label, componentId);
+ toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
+ }
+ if (toscaElement.isRight()) {
+ return Either.right(toscaElement.right().value());
+ }
+ return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value()));
+ }
+
+ private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) {
+ VertexTypeEnum label = componentV.getLabel();
+ switch (label) {
+ case NODE_TYPE:
+ return nodeTypeOperation;
+ case TOPOLOGY_TEMPLATE:
+ return topologyTemplateOperation;
+ default:
+ return null;
+ }
+ }
+
+ /**
+ *
+ * @param resource
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) {
+ ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource);
+
+ ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource);
+ Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement);
+ if (createToscaElement.isLeft()) {
+ log.debug("Component created successfully!!!");
+ T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value());
+ return Either.left(dataModel);
+ }
+ return Either.right(createToscaElement.right().value());
+ }
+
+ /**
+ *
+ * @param componentToDelete
+ * @return
+ */
+ public StorageOperationStatus markComponentToDelete(Component componentToDelete) {
+
+ if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) {
+ // component already marked for delete
+ return StorageOperationStatus.OK;
+ } else {
+
+ Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll);
+ if (getResponse.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentToDelete.getUniqueId(), getResponse.right().value());
+ return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value());
+
+ }
+ GraphVertex componentV = getResponse.left().value();
+
+ // same operation for node type and topology template operations
+ Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV);
+ if (result.isRight()) {
+ return result.right().value();
+ }
+ return StorageOperationStatus.OK;
+ }
+ }
+
+ /**
+ *
+ * @param componentId
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) {
+
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+ Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value());
+ if (deleteElement.isRight()) {
+ log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value());
+ return Either.right(deleteElement.right().value());
+ }
+ T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value());
+
+ return Either.left(dataModel);
+ }
+
+ private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) {
+ VertexTypeEnum label = componentV.getLabel();
+ Either<ToscaElement, StorageOperationStatus> toscaElement;
+ Object componentId = componentV.getUniqueId();
+ switch (label) {
+ case NODE_TYPE:
+ log.debug("Need to fetch node type for id {}", componentId);
+ toscaElement = nodeTypeOperation.deleteToscaElement(componentV);
+ break;
+ case TOPOLOGY_TEMPLATE:
+ log.debug("Need to fetch topology template for id {}", componentId);
+ toscaElement = topologyTemplateOperation.deleteToscaElement(componentV);
+ break;
+ default:
+ log.debug("not supported tosca type {} for id {}", label, componentId);
+ toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST);
+ break;
+ }
+ return toscaElement;
+ }
+
+ private ToscaElementOperation getToscaElementOperation(Component component) {
+ return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
+ return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
+
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
+ return getLatestByName(GraphPropertyEnum.NAME, resourceName);
+
+ }
+
+ public Either<Integer, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) {
+ Either<List<ToscaElement>, StorageOperationStatus> byCsar = null;
+
+ Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
+ properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
+
+ Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
+
+ if (resources.isRight()) {
+ if (resources.right().value() == TitanOperationStatus.NOT_FOUND) {
+ return Either.left(new Integer(0));
+ } else {
+ log.debug("failed to get resources from graph with property name: {}", csarUUID);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
+ }
+ }
+
+ List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
+
+ return Either.left(new Integer(resourceList.size()));
+
+ }
public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) {
- Either<List<ToscaElement>, StorageOperationStatus> followedResources;
- if (componentType == ComponentTypeEnum.RESOURCE) {
- followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
- } else {
- followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
- }
+ Either<List<ToscaElement>, StorageOperationStatus> followedResources;
+ if (componentType == ComponentTypeEnum.RESOURCE) {
+ followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
+ } else {
+ followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType);
+ }
Set<T> components = new HashSet<>();
- if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
- return Either.right(followedResources.right().value());
- }
- if (followedResources.isLeft()) {
- List<ToscaElement> toscaElements = followedResources.left().value();
- toscaElements.forEach(te -> {
- T component = ModelConverter.convertFromToscaElement(te);
- components.add(component);
- });
- }
- return Either.left(components);
- }
-
- public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
-
- return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
- }
-
- public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
-
- Either<Resource, StorageOperationStatus> result = null;
- Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>();
- props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
- props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
- Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag);
-
- if (getLatestRes.isRight()) {
- TitanOperationStatus status = getLatestRes.right().value();
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- if (result == null) {
- List<GraphVertex> resources = getLatestRes.left().value();
- double version = 0.0;
- GraphVertex highestResource = null;
- for (GraphVertex resource : resources) {
- double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
- if (resourceVersion > version) {
- version = resourceVersion;
- highestResource = resource;
- }
- }
- result = getToscaElement(highestResource.getUniqueId());
- }
- return result;
- }
+ if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) {
+ return Either.right(followedResources.right().value());
+ }
+ if (followedResources.isLeft()) {
+ List<ToscaElement> toscaElements = followedResources.left().value();
+ toscaElements.forEach(te -> {
+ T component = ModelConverter.convertFromToscaElement(te);
+ components.add(component);
+ });
+ }
+ return Either.left(components);
+ }
+
+ public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) {
+
+ return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata);
+ }
+
+ public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) {
+
+ Either<Resource, StorageOperationStatus> result = null;
+ Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>();
+ props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag);
+
+ if (getLatestRes.isRight()) {
+ TitanOperationStatus status = getLatestRes.right().value();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ if (result == null) {
+ List<GraphVertex> resources = getLatestRes.left().value();
+ double version = 0.0;
+ GraphVertex highestResource = null;
+ for (GraphVertex resource : resources) {
+ double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION));
+ if (resourceVersion > version) {
+ version = resourceVersion;
+ highestResource = resource;
+ }
+ }
+ result = getToscaElement(highestResource.getUniqueId());
+ }
+ return result;
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
+ Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
+ if (validateUniquenessRes.isLeft()) {
+ return Either.left(!validateUniquenessRes.left().value());
+ }
+ return validateUniquenessRes;
+ }
+
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
+ return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
+
+ }
+
+ public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
+ Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations);
+ if (status.isRight()) {
+ return status.right().value();
+ }
+ return StorageOperationStatus.OK;
+ }
+
+ protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
+
+ Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
+ properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
+
+ Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
+
+ if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("failed to get resources from graph with property name: {}", name);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
+ }
+ List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
+ if (resourceList != null && resourceList.size() > 0) {
+ if (log.isDebugEnabled()) {
+ StringBuilder builder = new StringBuilder();
+ for (GraphVertex resourceData : resourceList) {
+ builder.append(resourceData.getUniqueId() + "|");
+ }
+ log.debug("resources with property name:{} exists in graph. found {}", name, builder.toString());
+ }
+ return Either.left(false);
+ } else {
+ log.debug("resources with property name:{} does not exists in graph", name);
+ return Either.left(true);
+ }
+
+ }
+
+ /**
+ *
+ * @param newComponent
+ * @param oldComponent
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> overrideComponent(T newComponent, T oldComponent) {
+
+ // TODO
+ // newComponent.setInterfaces(oldComponent.getInterfaces);
+ newComponent.setArtifacts(oldComponent.getArtifacts());
+ newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts());
+ newComponent.setGroups(oldComponent.getGroups());
+ newComponent.setInputs(null);
+ newComponent.setLastUpdateDate(null);
+ newComponent.setHighestVersion(true);
+
+ Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (componentVEither.isRight()) {
+ log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value()));
+ }
+ GraphVertex componentv = componentVEither.left().value();
+ Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
+ if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value()));
+ }
+
+ Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
+ if (deleteToscaComponent.isRight()) {
+ log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
+ return Either.right(deleteToscaComponent.right().value());
+ }
+ Either<T, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
+ if (createToscaComponent.isRight()) {
+ log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
+ return Either.right(createToscaComponent.right().value());
+ }
+ T newElement = createToscaComponent.left().value();
+ Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
+ if (newVersionEither.isRight()) {
+ log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value()));
+ }
+ if (parentVertexEither.isLeft()) {
+ GraphVertex previousVersionV = parentVertexEither.left().value();
+ TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
+ if (createEdge != TitanOperationStatus.OK) {
+ log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge));
+ }
+ }
+ return Either.left(newElement);
+ }
+
+ /**
+ *
+ * @param componentToUpdate
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
+ return updateToscaElement(componentToUpdate, new ComponentParametersView());
+ }
+
+ /**
+ *
+ * @param componentToUpdate
+ * @param type
+ * @param filterResult
+ * @return
+ */
+ public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
+ String componentId = componentToUpdate.getUniqueId();
+ Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
+ if (getVertexEither.isRight()) {
+ log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+ }
+ GraphVertex elementV = getVertexEither.left().value();
+ ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
+
+ ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
+ Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
+ if (updateToscaElement.isRight()) {
+ log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value());
+ return Either.right(updateToscaElement.right().value());
+ }
+ return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value()));
+ }
+
+ private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
+ Either<T, StorageOperationStatus> result;
+
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ propertiesToMatch.put(property, nodeName);
+ propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata);
+ if (highestResources.isRight()) {
+ TitanOperationStatus status = highestResources.right().value();
+ log.debug("failed to find resource with name {}. status={} ", nodeName, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ return result;
+ }
+
+ List<GraphVertex> resources = highestResources.left().value();
+ double version = 0.0;
+ GraphVertex highestResource = null;
+ for (GraphVertex vertex : resources) {
+ Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
+ double resourceVersion = Double.valueOf((String) versionObj);
+ if (resourceVersion > version) {
+ version = resourceVersion;
+ highestResource = vertex;
+ }
+ }
+ return getToscaElementByOperation(highestResource);
+ }
+
+ public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
+
+ Either<List<T>, StorageOperationStatus> result = null;
+ Either<T, StorageOperationStatus> getComponentRes;
+ List<T> components = new ArrayList<>();
+ List<GraphVertex> componentVertices;
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
+ if (componentType != null)
+ propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+ if (getComponentsRes.isRight()) {
+ TitanOperationStatus status = getComponentsRes.right().value();
+ log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ if (result == null) {
+ componentVertices = getComponentsRes.left().value();
+ for (GraphVertex componentVertex : componentVertices) {
+ getComponentRes = getToscaElementByOperation(componentVertex);
+ if (getComponentRes.isRight()) {
+ log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
+ result = Either.right(getComponentRes.right().value());
+ break;
+ }
+ T componentBySystemName = getComponentRes.left().value();
+ log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
+ components.add(componentBySystemName);
+ }
+ }
+ if (result == null) {
+ result = Either.left(components);
+ }
+ return result;
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
+ return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
+ Either<T, StorageOperationStatus> result;
+
+ Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
+
+ hasProperties.put(GraphPropertyEnum.NAME, name);
+ hasProperties.put(GraphPropertyEnum.VERSION, version);
+ hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
+ if (componentType != null) {
+ hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+ }
+ Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
+ if (getResourceRes.isRight()) {
+ TitanOperationStatus status = getResourceRes.right().value();
+ log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ return result;
+ }
+ return getToscaElementByOperation(getResourceRes.left().value().get(0));
+ }
+
+ public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) {
+ List<T> components = new ArrayList<>();
+ Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
+ List<ToscaElement> toscaElements = new ArrayList<>();
+ List<ResourceTypeEnum> excludedResourceTypes =
+ Optional.ofNullable(excludeTypes).orElse(Collections.emptyList())
+ .stream()
+ .filter(type -> !type.equals(OriginTypeEnum.SERVICE))
+ .map(type -> ResourceTypeEnum.getTypeByName(type.name())).collect(Collectors.toList());
+
+ switch (componentType) {
+ case RESOURCE:
+ catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE,excludedResourceTypes , isHighestVersions);
+ if (catalogDataResult.isRight()) {
+ return Either.right(catalogDataResult.right().value());
+ }
+ toscaElements = catalogDataResult.left().value();
+ break;
+ case SERVICE:
+ if (excludeTypes!= null && excludeTypes.contains(OriginTypeEnum.SERVICE)) {
+ break;
+ }
+ catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions);
+ if (catalogDataResult.isRight()) {
+ return Either.right(catalogDataResult.right().value());
+ }
+ toscaElements = catalogDataResult.left().value();
+ break;
+ default:
+ log.debug("Not supported component type {}", componentType);
+ return Either.right(StorageOperationStatus.BAD_REQUEST);
+ }
+ toscaElements.forEach(te -> {
+ T component = ModelConverter.convertFromToscaElement(te);
+ components.add(component);
+ });
+ return Either.left(components);
+ }
+
+ public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
+ Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
+ List<String> deleted = new ArrayList<>();
+ switch (componentType) {
+ case RESOURCE:
+ allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
+ break;
+ case SERVICE:
+ case PRODUCT:
+ allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
+ break;
+ default:
+ log.debug("Not supported component type {}", componentType);
+ return Either.right(StorageOperationStatus.BAD_REQUEST);
+ }
+ if (allComponentsMarkedForDeletion.isRight()) {
+ return Either.right(allComponentsMarkedForDeletion.right().value());
+ }
+ List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
+
+ Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
+ if (allNotDeletedElements.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
+ }
+ List<GraphVertex> allNonMarked = allNotDeletedElements.left().value();
+ for (GraphVertex elementV : allMarked) {
+ if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) {
+ Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
+ if (deleteToscaElement.isRight()) {
+ log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value());
+ }
+ } else {
+ deleted.add(elementV.getUniqueId());
+ log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
+ }
+ }
+ return Either.left(deleted);
+ }
+
+ public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
+ Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
+ switch (componentType) {
+ case RESOURCE:
+ allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
+ break;
+ case SERVICE:
+ case PRODUCT:
+ allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
+ break;
+ default:
+ log.debug("Not supported component type {}", componentType);
+ return Either.right(StorageOperationStatus.BAD_REQUEST);
+ }
+ if (allComponentsMarkedForDeletion.isRight()) {
+ return Either.right(allComponentsMarkedForDeletion.right().value());
+ }
+ return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList()));
+ }
+
+ public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
+ Either<Boolean, StorageOperationStatus> result;
+ Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
+ if (allNotDeletedElements.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
+ } else {
+ result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value()));
+ }
+ return result;
+ }
+
+ public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
+
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
+ Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
+ componentInstance.setIcon(origComponent.getIcon());
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
+ ModelConverter.convertToToscaElement(origComponent), getNextComponentInstanceCounter(containerComponent, origComponent.getName()), componentInstance, allowDeleted, user);
+
+ if (addResult.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
+ result = Either.right(addResult.right().value());
+ }
+ if (result == null) {
+ updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
+ if (updateContainerComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
+ result = Either.right(updateContainerComponentRes.right().value());
+ }
+ }
+ if (result == null) {
+ Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
+ String createdInstanceId = addResult.left().value().getRight();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
+ result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
+ }
+ return result;
+ }
+
+ public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) {
+
+ StorageOperationStatus result = null;
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
+
+ Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
+ if (metadataVertex.isRight()) {
+ TitanOperationStatus status = metadataVertex.right().value();
+ if (status == TitanOperationStatus.NOT_FOUND) {
+ status = TitanOperationStatus.INVALID_ID;
+ }
+ result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
+ }
+ if (result == null) {
+ result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted);
+ }
+ return result;
+ }
+
+ public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
+
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
+
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
+ componentInstance.setIcon(origComponent.getIcon());
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
+ ModelConverter.convertToToscaElement(origComponent), componentInstance);
+ if (updateResult.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
+ result = Either.right(updateResult.right().value());
+ }
+ if (result == null) {
+ Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
+ String createdInstanceId = updateResult.left().value().getRight();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
+ result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
+ }
+ return result;
+ }
+
+ public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
+
+ Either<Component, StorageOperationStatus> result = null;
+
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
+
+ Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent));
+ if (updateResult.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
+ result = Either.right(updateResult.right().value());
+ }
+ if (result == null) {
+ Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
+ result = Either.left(updatedComponent);
+ }
+ return result;
+ }
+
+ public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
+
+ Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
+
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
+
+ Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
+ if (updateResult.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
+ result = Either.right(updateResult.right().value());
+ }
+ if (result == null) {
+ Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
+ String deletedInstanceId = updateResult.left().value().getRight();
+ CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
+ result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
+ }
+ return result;
+ }
+
+ private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
+
+ Integer nextCounter = 0;
+
+ if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
+
+ String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
+ Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName);
+ Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName);
+
+ if (maxCounterFromNames == null && maxCounterFromIds != null) {
+ nextCounter = maxCounterFromIds + 1;
+ } else if (maxCounterFromIds == null && maxCounterFromNames != null) {
+ nextCounter = maxCounterFromNames + 1;
+ } else if (maxCounterFromIds != null && maxCounterFromNames != null) {
+ nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1;
+ }
+ }
+ return nextCounter.toString();
+ }
+
+ private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) {
+
+ Integer maxCounter = 0;
+ List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1])
+ .collect(Collectors.toList());
+
+ if (CollectionUtils.isEmpty(countersStr)) {
+ return null;
+ }
+ Integer currCounter = null;
+ for (String counter : countersStr) {
+ if (StringUtils.isEmpty(counter)) {
+ continue;
+ }
+ try {
+ currCounter = Integer.parseInt(counter);
+ } catch (Exception e) {
+ continue;
+ }
+ maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
+ }
+ if (currCounter == null) {
+ return null;
+ }
+ return maxCounter;
+ }
+
+ private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) {
+
+ Integer maxCounter = 0;
+ List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1])
+ .collect(Collectors.toList());
+
+ if (CollectionUtils.isEmpty(countersStr)) {
+ return null;
+ }
+ Integer currCounter = null;
+ for (String counter : countersStr) {
+ if (StringUtils.isEmpty(counter)) {
+ continue;
+ }
+ try {
+ currCounter = Integer.parseInt(counter);
+ } catch (Exception e) {
+ continue;
+ }
+ maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
+ }
+ if (currCounter == null) {
+ return null;
+ }
+ return maxCounter;
+ }
+
+ public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
+ return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
+
+ }
+
+ public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
+
+ 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 Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
+
+ StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
+
+ if (StorageOperationStatus.OK == status) {
+ log.debug("Component created successfully!!!");
+ List<InputDefinition> inputsResList = null;
+ if (inputsMap != null && !inputsMap.isEmpty()) {
+ inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
+ }
+ return Either.left(inputsResList);
+ }
+ return Either.right(status);
+
+ }
+
+ public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
+
+ 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 Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
+
+ StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
+
+ if (StorageOperationStatus.OK == status) {
+ log.debug("Component created successfully!!!");
+ List<InputDefinition> inputsResList = null;
+ if (inputsMap != null && !inputsMap.isEmpty()) {
+ inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
+ }
+ return Either.left(inputsResList);
+ }
+ return Either.right(status);
+
+ }
+
+ public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
+
+ 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 Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
+
+ }
+
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
+ if (instProperties != null) {
- public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) {
- Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName);
- if (validateUniquenessRes.isLeft()) {
- return Either.left(!validateUniquenessRes.left().value());
- }
- return validateUniquenessRes;
- }
-
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
- return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef);
-
- }
-
- public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
- Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations);
- if (status.isRight()) {
- return status.right().value();
- }
- return StorageOperationStatus.OK;
- }
-
- protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) {
-
- Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>();
- properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name);
-
- Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata);
-
- if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("failed to get resources from graph with property name: {}", name);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()));
- }
- List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null);
- if (resourceList != null && resourceList.size() > 0) {
- if (log.isDebugEnabled()) {
- StringBuilder builder = new StringBuilder();
- for (GraphVertex resourceData : resourceList) {
- builder.append(resourceData.getUniqueId() + "|");
- }
- log.debug("resources with property name:{} exists in graph. found {}", name, builder.toString());
- }
- return Either.left(false);
- } else {
- log.debug("resources with property name:{} does not exists in graph", name);
- return Either.left(true);
- }
-
- }
-
- /**
- *
- * @param newComponent
- * @param oldComponent
- * @return
- */
- public <T extends Component> Either<T, StorageOperationStatus> overrideComponent(T newComponent, T oldComponent) {
-
- // TODO
- // newComponent.setInterfaces(oldComponent.getInterfaces);
- newComponent.setArtifacts(oldComponent.getArtifacts());
- newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts());
- newComponent.setGroups(oldComponent.getGroups());
- newComponent.setInputs(null);
- newComponent.setLastUpdateDate(null);
- newComponent.setHighestVersion(true);
-
- Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse);
- if (componentVEither.isRight()) {
- log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value()));
- }
- GraphVertex componentv = componentVEither.left().value();
- Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse);
- if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value()));
- }
-
- Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv);
- if (deleteToscaComponent.isRight()) {
- log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value());
- return Either.right(deleteToscaComponent.right().value());
- }
- Either<T, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent);
- if (createToscaComponent.isRight()) {
- log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value());
- return Either.right(createToscaComponent.right().value());
- }
- T newElement = createToscaComponent.left().value();
- Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse);
- if (newVersionEither.isRight()) {
- log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value()));
- }
- if (parentVertexEither.isLeft()) {
- GraphVertex previousVersionV = parentVertexEither.left().value();
- TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null);
- if (createEdge != TitanOperationStatus.OK) {
- log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge));
- }
- }
- return Either.left(newElement);
- }
-
- /**
- *
- * @param componentToUpdate
- * @return
- */
- public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) {
- return updateToscaElement(componentToUpdate, new ComponentParametersView());
- }
+ MapPropertiesDataDefinition propertiesMap;
+ for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
+ propertiesMap = new MapPropertiesDataDefinition();
- /**
- *
- * @param componentToUpdate
- * @param type
- * @param filterResult
- * @return
- */
- public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) {
- String componentId = componentToUpdate.getUniqueId();
- Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
- if (getVertexEither.isRight()) {
- log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
- }
- GraphVertex elementV = getVertexEither.left().value();
- ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV);
-
- ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate);
- Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult);
- if (updateToscaElement.isRight()) {
- log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value());
- return Either.right(updateToscaElement.right().value());
- }
- return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value()));
- }
-
- private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
- Either<T, StorageOperationStatus> result;
-
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
+
+ instPropsMap.put(entry.getKey(), propertiesMap);
+ }
+ }
+
+ StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
- propertiesToMatch.put(property, nodeName);
- propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ if (StorageOperationStatus.OK == status) {
+ log.debug("Component created successfully!!!");
+ return Either.left(instProperties);
+ }
+ return Either.right(status);
- propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
-
- Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata);
- if (highestResources.isRight()) {
- TitanOperationStatus status = highestResources.right().value();
- log.debug("failed to find resource with name {}. status={} ", nodeName, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
-
- List<GraphVertex> resources = highestResources.left().value();
- double version = 0.0;
- GraphVertex highestResource = null;
- for (GraphVertex vertex : resources) {
- Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
- double resourceVersion = Double.valueOf((String) versionObj);
- if (resourceVersion > version) {
- version = resourceVersion;
- highestResource = vertex;
- }
- }
- return getToscaElementByOperation(highestResource);
- }
-
- public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
-
- Either<List<T>, StorageOperationStatus> result = null;
- Either<T, StorageOperationStatus> getComponentRes;
- List<T> components = new ArrayList<>();
- List<GraphVertex> componentVertices;
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
- propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
- if (componentType != null)
- propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
-
- propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
-
- Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
- if (getComponentsRes.isRight()) {
- TitanOperationStatus status = getComponentsRes.right().value();
- log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- if (result == null) {
- componentVertices = getComponentsRes.left().value();
- for (GraphVertex componentVertex : componentVertices) {
- getComponentRes = getToscaElementByOperation(componentVertex);
- if (getComponentRes.isRight()) {
- log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value());
- result = Either.right(getComponentRes.right().value());
- break;
- }
- T componentBySystemName = getComponentRes.left().value();
- log.debug("Found component, id: {}", componentBySystemName.getUniqueId());
- components.add(componentBySystemName);
- }
- }
- if (result == null) {
- result = Either.left(components);
- }
- return result;
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) {
- return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll);
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) {
- Either<T, StorageOperationStatus> result;
-
- Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
-
- hasProperties.put(GraphPropertyEnum.NAME, name);
- hasProperties.put(GraphPropertyEnum.VERSION, version);
- hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
- if (componentType != null) {
- hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
- }
- Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
- if (getResourceRes.isRight()) {
- TitanOperationStatus status = getResourceRes.right().value();
- log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- return getToscaElementByOperation(getResourceRes.left().value().get(0));
- }
-
- public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, boolean isHighestVersions) {
- List<T> components = new ArrayList<>();
- Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult;
- List<ToscaElement> toscaElements;
- switch (componentType) {
- case RESOURCE:
- catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, ToscaElementTypeEnum.NodeType, isHighestVersions);
- if (catalogDataResult.isRight()) {
- return Either.right(catalogDataResult.right().value());
- }
- toscaElements = catalogDataResult.left().value();
- Either<List<ToscaElement>, StorageOperationStatus> resourceCatalogData = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, ToscaElementTypeEnum.TopologyTemplate, isHighestVersions);
- if (resourceCatalogData.isRight()) {
- return Either.right(resourceCatalogData.right().value());
- }
- toscaElements.addAll(resourceCatalogData.left().value());
- break;
- case SERVICE:
- catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, ToscaElementTypeEnum.TopologyTemplate, isHighestVersions);
- if (catalogDataResult.isRight()) {
- return Either.right(catalogDataResult.right().value());
- }
- toscaElements = catalogDataResult.left().value();
- break;
- default:
- log.debug("Not supported component type {}", componentType);
- return Either.right(StorageOperationStatus.BAD_REQUEST);
- }
- toscaElements.forEach(te -> {
- T component = ModelConverter.convertFromToscaElement(te);
- components.add(component);
- });
- return Either.left(components);
- }
-
- public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) {
- Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
- List<String> deleted = new ArrayList<>();
- switch (componentType) {
- case RESOURCE:
- allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
- break;
- case SERVICE:
- case PRODUCT:
- allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
- break;
- default:
- log.debug("Not supported component type {}", componentType);
- return Either.right(StorageOperationStatus.BAD_REQUEST);
- }
- if (allComponentsMarkedForDeletion.isRight()) {
- return Either.right(allComponentsMarkedForDeletion.right().value());
- }
- List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value();
-
- Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
- if (allNotDeletedElements.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
- }
- List<GraphVertex> allNonMarked = allNotDeletedElements.left().value();
- for (GraphVertex elementV : allMarked) {
- if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) {
- Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV);
- if (deleteToscaElement.isRight()) {
- log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value());
- }
- } else {
- deleted.add(elementV.getUniqueId());
- log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId());
- }
- }
- return Either.left(deleted);
- }
-
- public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) {
- Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion;
- switch (componentType) {
- case RESOURCE:
- allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType);
- break;
- case SERVICE:
- case PRODUCT:
- allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType);
- break;
- default:
- log.debug("Not supported component type {}", componentType);
- return Either.right(StorageOperationStatus.BAD_REQUEST);
- }
- if (allComponentsMarkedForDeletion.isRight()) {
- return Either.right(allComponentsMarkedForDeletion.right().value());
- }
- return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList()));
- }
-
- public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) {
- Either<Boolean, StorageOperationStatus> result;
- Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements();
- if (allNotDeletedElements.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value()));
- } else {
- result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value()));
- }
- return result;
- }
-
- public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) {
-
- Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
- Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
- componentInstance.setIcon(origComponent.getIcon());
- Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
- ModelConverter.convertToToscaElement(origComponent), getNextComponentInstanceCounter(containerComponent, origComponent.getName()), componentInstance, allowDeleted, user);
-
- if (addResult.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName());
- result = Either.right(addResult.right().value());
- }
- if (result == null) {
- updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId());
- if (updateContainerComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName());
- result = Either.right(updateContainerComponentRes.right().value());
- }
- }
- if (result == null) {
- Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value());
- String createdInstanceId = addResult.left().value().getRight();
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName());
- result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
- }
- return result;
- }
-
- public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) {
-
- StorageOperationStatus result = null;
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId());
-
- Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll);
- if (metadataVertex.isRight()) {
- TitanOperationStatus status = metadataVertex.right().value();
- if (status == TitanOperationStatus.NOT_FOUND) {
- status = TitanOperationStatus.INVALID_ID;
- }
- result = DaoStatusConverter.convertTitanStatusToStorageStatus(status);
- }
- if (result == null) {
- result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted);
- }
- return result;
- }
-
- public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) {
-
- Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
-
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
- componentInstance.setIcon(origComponent.getIcon());
- Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent),
- ModelConverter.convertToToscaElement(origComponent), componentInstance);
- if (updateResult.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName());
- result = Either.right(updateResult.right().value());
- }
- if (result == null) {
- Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
- String createdInstanceId = updateResult.left().value().getRight();
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName());
- result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId));
- }
- return result;
- }
-
- public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) {
-
- Either<Component, StorageOperationStatus> result = null;
-
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName());
-
- Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent));
- if (updateResult.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName());
- result = Either.right(updateResult.right().value());
- }
- if (result == null) {
- Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value());
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName());
- result = Either.left(updatedComponent);
- }
- return result;
- }
-
- public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) {
-
- Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null;
-
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
-
- Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId);
- if (updateResult.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName());
- result = Either.right(updateResult.right().value());
- }
- if (result == null) {
- Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft());
- String deletedInstanceId = updateResult.left().value().getRight();
- CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName());
- result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId));
- }
- return result;
- }
-
- private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) {
-
- Integer nextCounter = 0;
-
- if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
-
- String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName);
- Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName);
- Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName);
-
- if (maxCounterFromNames == null && maxCounterFromIds != null) {
- nextCounter = maxCounterFromIds + 1;
- } else if (maxCounterFromIds == null && maxCounterFromNames != null) {
- nextCounter = maxCounterFromNames + 1;
- } else if (maxCounterFromIds != null && maxCounterFromNames != null) {
- nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1;
- }
- }
- return nextCounter.toString();
- }
-
- private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) {
-
- Integer maxCounter = 0;
- List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1])
- .collect(Collectors.toList());
-
- if (CollectionUtils.isEmpty(countersStr)) {
- return null;
- }
- Integer currCounter = null;
- for (String counter : countersStr) {
- if (StringUtils.isEmpty(counter)) {
- continue;
- }
- try {
- currCounter = Integer.parseInt(counter);
- } catch (Exception e) {
- continue;
- }
- maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
- }
- if (currCounter == null) {
- return null;
- }
- return maxCounter;
- }
-
- private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) {
-
- Integer maxCounter = 0;
- List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1])
- .collect(Collectors.toList());
-
- if (CollectionUtils.isEmpty(countersStr)) {
- return null;
- }
- Integer currCounter = null;
- for (String counter : countersStr) {
- if (StringUtils.isEmpty(counter)) {
- continue;
- }
- try {
- currCounter = Integer.parseInt(counter);
- } catch (Exception e) {
- continue;
- }
- maxCounter = maxCounter < currCounter ? currCounter : maxCounter;
- }
- if (currCounter == null) {
- return null;
- }
- return maxCounter;
- }
-
- public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
- return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef);
-
- }
-
- public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) {
-
- 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 Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
-
- }
-
- GraphVertex vertex = getVertexEither.left().value();
- Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
-
- StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId);
-
- if (StorageOperationStatus.OK == status) {
- log.debug("Component created successfully!!!");
- List<InputDefinition> inputsResList = null;
- if (inputsMap != null && !inputsMap.isEmpty()) {
- inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
- }
- return Either.left(inputsResList);
- }
- return Either.right(status);
-
- }
-
- public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) {
-
- 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 Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
-
- }
-
- GraphVertex vertex = getVertexEither.left().value();
- Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue())));
-
- StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME);
-
- if (StorageOperationStatus.OK == status) {
- log.debug("Component created successfully!!!");
- List<InputDefinition> inputsResList = null;
- if (inputsMap != null && !inputsMap.isEmpty()) {
- inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList());
- }
- return Either.left(inputsResList);
- }
- return Either.right(status);
-
- }
-
- public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
+ }
+ public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) {
Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse);
if (getVertexEither.isRight()) {
@@ -1021,13 +990,12 @@ public class ToscaOperationFacade {
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()));
}
-
GraphVertex vertex = getVertexEither.left().value();
Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
- if (instProperties != null) {
+ if (instInputs != null) {
MapPropertiesDataDefinition propertiesMap;
- for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
+ for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) {
propertiesMap = new MapPropertiesDataDefinition();
propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
@@ -1036,551 +1004,553 @@ public class ToscaOperationFacade {
}
}
- StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap);
+ StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap);
if (StorageOperationStatus.OK == status) {
log.debug("Component created successfully!!!");
- return Either.left(instProperties);
+ return Either.left(instInputs);
}
return Either.right(status);
}
+ public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
+
+ StorageOperationStatus status = StorageOperationStatus.OK;
+ if (instProperties != null) {
+
+ for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
+ List<ComponentInstanceInput> props = entry.getValue();
+ String componentInstanseId = entry.getKey();
+ if (props != null && !props.isEmpty()) {
+ for (ComponentInstanceInput property : props) {
+ List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId);
+ Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream().filter(p -> p.getName().equals(property.getName())).findAny();
+ if (instanceProperty.isPresent()) {
+ status = updateComponentInstanceInput(containerComponent, componentInstanseId, property);
+ } else {
+ status = addComponentInstanceInput(containerComponent, componentInstanseId, property);
+ }
+ if (status != StorageOperationStatus.OK) {
+ log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanseId, status);
+ return Either.right(status);
+ } else {
+ log.trace("instance input {} for instance {} updated", property, componentInstanseId);
+ }
+ }
+ }
+ }
+ }
+ return Either.left(instProperties);
+ }
+
+ public StorageOperationStatus deleteComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instProperties, String componentId) {
- public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) {
-
- StorageOperationStatus status = StorageOperationStatus.OK;
- if (instProperties != null) {
-
- for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
- List<ComponentInstanceInput> props = entry.getValue();
- String componentInstanseId = entry.getKey();
- if (props != null && !props.isEmpty()) {
- for (ComponentInstanceInput property : props) {
- List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId);
- Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream().filter(p -> p.getName().equals(property.getName())).findAny();
- if (instanceProperty.isPresent()) {
- status = updateComponentInstanceInput(containerComponent, componentInstanseId, property);
- } else {
- status = addComponentInstanceInput(containerComponent, componentInstanseId, property);
- }
- if (status != StorageOperationStatus.OK) {
- log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanseId, status);
- return Either.right(status);
- } else {
- log.trace("instance input {} for instance {} updated", property, componentInstanseId);
- }
- }
- }
- }
- }
- return Either.left(instProperties);
- }
+ 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());
- public StorageOperationStatus deleteComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instProperties, String componentId) {
+ }
- 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, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
+ if (instProperties != null) {
- }
+ MapPropertiesDataDefinition propertiesMap;
+ for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
+ propertiesMap = new MapPropertiesDataDefinition();
- GraphVertex vertex = getVertexEither.left().value();
- Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>();
- if (instProperties != null) {
+ propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
- MapPropertiesDataDefinition propertiesMap;
- for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) {
- propertiesMap = new MapPropertiesDataDefinition();
-
- propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
-
- instPropsMap.put(entry.getKey(), propertiesMap);
- }
- }
-
- return topologyTemplateOperation.deleteInstInputsToComponent(vertex, instPropsMap);
-
- }
-
- public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
-
- StorageOperationStatus status = StorageOperationStatus.OK;
- if (instProperties != null) {
-
- for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
- List<ComponentInstanceProperty> props = entry.getValue();
- String componentInstanseId = entry.getKey();
- List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId);
- if (props != null && !props.isEmpty()) {
- for (ComponentInstanceProperty property : props) {
- Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
- if (instanceProperty.isPresent()) {
- status = updateComponentInstanceProperty(containerComponent, componentInstanseId, property);
- } else {
- status = addComponentInstanceProperty(containerComponent, componentInstanseId, property);
- }
-
- }
- }
- }
- }
-
- return Either.left(instProperties);
-
- }
-
- public StorageOperationStatus associateArtifactToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, 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 (instArtifacts != null) {
-
- MapArtifactDataDefinition artifactsMap;
- 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);
-
- instArtMap.put(entry.getKey(), artifactsMap);
- }
- }
-
- return topologyTemplateOperation.associateInstArtifactToComponent(vertex, instArtMap);
-
- }
-
- public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) {
-
- 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, MapPropertiesDataDefinition> instAttr = new HashMap<>();
- if (instArttributes != null) {
-
- MapPropertiesDataDefinition attributesMap;
- for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) {
- attributesMap = new MapPropertiesDataDefinition();
- attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
- instAttr.put(entry.getKey(), attributesMap);
- }
- }
-
- return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
-
- }
-
- public StorageOperationStatus associateCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) {
- 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, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
-
- Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>();
- Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>();
- ;
- if (instCapabilties != null) {
- for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
-
- Map<String, List<CapabilityDefinition>> caps = entry.getValue();
- Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
- for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
- mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList())));
- }
-
- ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
- MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
-
- MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
-
- calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
- calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty);
- }
- }
-
- if (instReg != null) {
- for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
-
- Map<String, List<RequirementDefinition>> req = entry.getValue();
- Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
- for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
- mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList())));
- }
-
- MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
-
- calcRequirements.put(entry.getKey().getUniqueId(), capMap);
- }
- }
-
- StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
-
- return status;
- }
-
- private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
-
- Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
-
- fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
-
- Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
- if (getRes.isRight()) {
- if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
- return Either.left(new ArrayList<>());
- } else {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
- }
- } else {
- List<Component> nonAbstractLatestComponents = new ArrayList<>();
- ComponentParametersView params = new ComponentParametersView(true);
- params.setIgnoreAllVersions(false);
- for (GraphVertex vertexComponent : getRes.left().value()) {
- Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
- if (componentRes.isRight()) {
- log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
- return Either.right(componentRes.right().value());
- } else {
- Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
-
- nonAbstractLatestComponents.add(component);
- }
- }
-
- return Either.left(nonAbstractLatestComponents);
- }
- }
-
- public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
+ instPropsMap.put(entry.getKey(), propertiesMap);
+ }
+ }
- Either<ComponentMetadataData, StorageOperationStatus> result;
+ return topologyTemplateOperation.deleteInstInputsToComponent(vertex, instPropsMap);
- Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
-
- hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
- if (isHighest != null) {
- hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
- }
-
- Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
- propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
-
- Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
- if (getRes.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
- } else {
- List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
- ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
- : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
- result = Either.left(latestVersion);
- }
- return result;
- }
+ }
- public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
+ public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) {
- Either<ComponentMetadataData, StorageOperationStatus> result;
- Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
- if (getRes.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
- } else {
- ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
- result = Either.left(componentMetadata);
- }
- return result;
- }
+ StorageOperationStatus status = StorageOperationStatus.OK;
+ if (instProperties != null) {
- 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());
+ for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) {
+ List<ComponentInstanceProperty> props = entry.getValue();
+ String componentInstanseId = entry.getKey();
+ List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId);
+ if (props != null && !props.isEmpty()) {
+ for (ComponentInstanceProperty property : props) {
+ Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
+ if (instanceProperty.isPresent()) {
+ status = updateComponentInstanceProperty(containerComponent, componentInstanseId, property);
+ } else {
+ status = addComponentInstanceProperty(containerComponent, componentInstanseId, property);
+ }
- 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 Either.left(instProperties);
- return resVersionMap;
- }
+ }
- private Pair<String, String> createKeyPair(ComponentMetadataData metadataData) {
- Pair<String, String> pair;
- NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel());
- switch (label) {
- case Resource:
- pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name());
- break;
- default:
- pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel());
- break;
- }
+ public StorageOperationStatus associateArtifactToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) {
- return pair;
- }
+ 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());
- public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
+ }
- Either<List<Component>, StorageOperationStatus> result = null;
- List<Component> components = new ArrayList<>();
- if (componentUids == null) {
- Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids);
- if (componentUidsRes.isRight()) {
- result = Either.right(componentUidsRes.right().value());
- } else {
- componentUids = componentUidsRes.left().value();
- }
- }
- if (!componentUids.isEmpty()) {
- for (String componentUid : componentUids) {
- ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
- if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) {
- componentParametersView.setIgnoreCapabilities(false);
- componentParametersView.setIgnoreRequirements(false);
- }
- Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
- if (getToscaElementRes.isRight()) {
- if (log.isDebugEnabled())
- log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
- result = Either.right(getToscaElementRes.right().value());
- break;
- }
- Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.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);
- components.add(component);
- }
- }
- if (result == null) {
- result = Either.left(components);
- }
- return result;
- }
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>();
+ if (instArtifacts != null) {
- private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
-
- Either<List<String>, StorageOperationStatus> result = null;
- Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType);
- if (getToscaElementsRes.isRight()) {
- result = Either.right(getToscaElementsRes.right().value());
- } else {
- List<Component> collection = getToscaElementsRes.left().value();
- if (collection == null) {
- componentUids = new ArrayList<>();
- } else {
- componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
- }
- }
- if (result == null) {
- result = Either.left(componentUids);
- }
- return result;
- }
+ MapArtifactDataDefinition artifactsMap;
+ 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);
- private ComponentParametersView buildComponentViewForNotAbstract() {
- ComponentParametersView componentParametersView = new ComponentParametersView();
- componentParametersView.disableAll();
- componentParametersView.setIgnoreCategories(false);
- componentParametersView.setIgnoreAllVersions(false);
- return componentParametersView;
- }
+ instArtMap.put(entry.getKey(), artifactsMap);
+ }
+ }
+
+ return topologyTemplateOperation.associateInstArtifactToComponent(vertex, instArtMap);
+
+ }
+
+ public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) {
+
+ 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());
- public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
- Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
- if (result.isLeft()) {
- result = Either.left(!result.left().value());
- }
- return result;
- }
+ }
- public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
- VertexTypeEnum vertexType = getVertexTypeByComponentAndResourceTypeEnum(resourceType, componentType);
- String normalizedName = ValidationUtils.normaliseComponentName(name);
- Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
- properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
- properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
-
- Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
- if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
- log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
- }
- List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
- if (vertexList != null && !vertexList.isEmpty()) {
- return Either.left(false);
- } else {
- return Either.left(true);
- }
- }
+ GraphVertex vertex = getVertexEither.left().value();
+ Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>();
+ if (instArttributes != null) {
- // UI query parameter is either VFC/CP/VL(for yaml upload/update) or VF (for CSAR upload/user composed VF)
- // TODO implementation of topology template VFCs may require updating this method - depending on UI implementation
- private VertexTypeEnum getVertexTypeByComponentAndResourceTypeEnum(ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
- VertexTypeEnum vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE;
- if (ComponentTypeEnum.RESOURCE == componentType && ResourceTypeEnum.VF != resourceType) {
- vertexType = VertexTypeEnum.NODE_TYPE;
- }
- return vertexType;
- }
+ MapPropertiesDataDefinition attributesMap;
+ for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) {
+ attributesMap = new MapPropertiesDataDefinition();
+ attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e)));
+ instAttr.put(entry.getKey(), attributesMap);
+ }
+ }
- private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) {
- switch (internalComponentType.toLowerCase()) {
- case "vf":
- hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF.name());
- hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name());
- break;
- case "service":
- hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFC.name());
- hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name());
- break;
- case "vl":
- hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name());
- break;
- default:
- break;
- }
- }
+ return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr);
- private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, ComponentTypeEnum componentTypeEnum) {
- switch (componentTypeEnum) {
- case RESOURCE:
- hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
- break;
- case SERVICE:
- hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
- break;
- default:
- break;
- }
- }
+ }
- private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
- hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+ public StorageOperationStatus associateCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) {
+ 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());
- hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
- hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
- hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
- if (internalComponentType != null) {
- fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
- }
- } else {
- fillTopologyTemplatePropsMap(hasProps, componentTypeEnum);
- }
- }
+ }
- private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
- List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
- if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
- internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
- }
- if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType)) {
- internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
- }
- return internalVertexTypes;
- }
+ GraphVertex vertex = getVertexEither.left().value();
- public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
- List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
- List<Component> result = new ArrayList<>();
- for (VertexTypeEnum vertexType : internalVertexTypes) {
- Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType);
- if (listByVertexType.isRight()) {
- return listByVertexType;
- }
- result.addAll(listByVertexType.left().value());
- }
- return Either.left(result);
+ Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>();
- }
+ Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>();
+ Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>();
+ ;
+ if (instCapabilties != null) {
+ for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
- public Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) {
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ Map<String, List<CapabilityDefinition>> caps = entry.getValue();
+ Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>();
+ for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) {
+ mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList())));
+ }
+
+ ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey());
+ MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance);
+
+ MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true);
+
+ calcCapabilty.put(entry.getKey().getUniqueId(), capMap);
+ calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty);
+ }
+ }
+
+ if (instReg != null) {
+ for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
+
+ Map<String, List<RequirementDefinition>> req = entry.getValue();
+ Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>();
+ for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) {
+ mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList())));
+ }
+
+ MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey()));
+
+ calcRequirements.put(entry.getKey().getUniqueId(), capMap);
+ }
+ }
+
+ StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties);
+
+ return status;
+ }
+
+ private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) {
+
+ Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
+
+ fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
+ if (getRes.isRight()) {
+ if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) {
+ return Either.left(new ArrayList<>());
+ } else {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
+ }
+ } else {
+ List<Component> nonAbstractLatestComponents = new ArrayList<>();
+ ComponentParametersView params = new ComponentParametersView(true);
+ params.setIgnoreAllVersions(false);
+ for (GraphVertex vertexComponent : getRes.left().value()) {
+ Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params);
+ if (componentRes.isRight()) {
+ log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
+ return Either.right(componentRes.right().value());
+ } else {
+ Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
+
+ nonAbstractLatestComponents.add(component);
+ }
+ }
+
+ return Either.left(nonAbstractLatestComponents);
+ }
+ }
+
+ public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) {
+
+ Either<ComponentMetadataData, StorageOperationStatus> result;
+
+ Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
+
+ hasProperties.put(GraphPropertyEnum.UUID, componentUuid);
+ if (isHighest != null) {
+ hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
+ }
+
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag);
+ if (getRes.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
+ } else {
+ List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList());
+ ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0)
+ : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get();
+ result = Either.left(latestVersion);
+ }
+ return result;
+ }
+
+ public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) {
+
+ Either<ComponentMetadataData, StorageOperationStatus> result;
+ Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata);
+ if (getRes.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
+ } else {
+ ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value());
+ result = Either.left(componentMetadata);
+ }
+ return result;
+ }
+
+ 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;
+ NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel());
+ switch (label) {
+ case Resource:
+ pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name());
+ break;
+ default:
+ pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel());
+ break;
+ }
+
+ return pair;
+ }
+
+ public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
+
+ Either<List<Component>, StorageOperationStatus> result = null;
+ List<Component> components = new ArrayList<>();
+ if (componentUids == null) {
+ Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids);
+ if (componentUidsRes.isRight()) {
+ result = Either.right(componentUidsRes.right().value());
+ } else {
+ componentUids = componentUidsRes.left().value();
+ }
+ }
+ if (!componentUids.isEmpty()) {
+ for (String componentUid : componentUids) {
+ ComponentParametersView componentParametersView = buildComponentViewForNotAbstract();
+ if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) {
+ componentParametersView.setIgnoreCapabilities(false);
+ componentParametersView.setIgnoreRequirements(false);
+ }
+ Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView);
+ if (getToscaElementRes.isRight()) {
+ if (log.isDebugEnabled())
+ log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value());
+ result = Either.right(getToscaElementRes.right().value());
+ break;
+ }
+ Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.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);
+ components.add(component);
+ }
+ }
+ if (result == null) {
+ result = Either.left(components);
+ }
+ return result;
+ }
+
+ private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) {
+
+ Either<List<String>, StorageOperationStatus> result = null;
+ Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType);
+ if (getToscaElementsRes.isRight()) {
+ result = Either.right(getToscaElementsRes.right().value());
+ } else {
+ List<Component> collection = getToscaElementsRes.left().value();
+ if (collection == null) {
+ componentUids = new ArrayList<>();
+ } else {
+ componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
+ }
+ }
+ if (result == null) {
+ result = Either.left(componentUids);
+ }
+ return result;
+ }
+
+ private ComponentParametersView buildComponentViewForNotAbstract() {
+ ComponentParametersView componentParametersView = new ComponentParametersView();
+ componentParametersView.disableAll();
+ componentParametersView.setIgnoreCategories(false);
+ componentParametersView.setIgnoreAllVersions(false);
+ return componentParametersView;
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
+ Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType);
+ if (result.isLeft()) {
+ result = Either.left(!result.left().value());
+ }
+ return result;
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) {
+ VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
+ String normalizedName = ValidationUtils.normaliseComponentName(name);
+ Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
+ properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
+ properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+
+ Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
+ if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) {
+ log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
+ }
+ List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
+ if (vertexList != null && !vertexList.isEmpty()) {
+ return Either.left(false);
+ } else {
+ return Either.left(true);
+ }
+ }
+
+
+ private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) {
+ switch (internalComponentType.toLowerCase()) {
+ case "vf":
+ case "cvfc":
+ hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name());
+ break;
+ case "service":
+ case "pnf" :
+ hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name()));
+ break;
+ case "vl":
+ hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name());
+ break;
+ default:
+ break;
+ }
+ }
+
+
+ private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
+ switch (componentTypeEnum) {
+ case RESOURCE:
+ hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ break;
+ case SERVICE:
+ hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ break;
+ default:
+ break;
+ }
+ switch (internalComponentType.toLowerCase()) {
+ case "vf":
+ case "cvfc":
+ hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
+ break;
+ case "service":
+ hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name());
+ break;
+ default:
+ break;
+ }
+ }
+
+ private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
+ hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+
+ hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
+ hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
+ hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
+ if (internalComponentType != null) {
+ fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
+ }
+ } else {
+ fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum, internalComponentType);
+ }
+ }
+
+ private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) {
+ List<VertexTypeEnum> internalVertexTypes = new ArrayList<>();
+ if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
+ internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
+ }
+ if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType) || "vf".equalsIgnoreCase(internalComponentType)) {
+ internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ }
+ return internalVertexTypes;
+ }
+
+ public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) {
+ List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
+ List<Component> result = new ArrayList<>();
+ for (VertexTypeEnum vertexType : internalVertexTypes) {
+ Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType);
+ if (listByVertexType.isRight()) {
+ return listByVertexType;
+ }
+ result.addAll(listByVertexType.left().value());
+ }
+ return Either.left(result);
+
+ }
+
+ public Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) {
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
Either<List<Component>, StorageOperationStatus> componentListByUuid = getComponentListByUuid(componentUuid, propertiesToMatch);
return componentListByUuid;
- }
+ }
- public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
+ public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- if (additionalPropertiesToMatch != null) {
- propertiesToMatch.putAll(additionalPropertiesToMatch);
- }
+ if (additionalPropertiesToMatch != null) {
+ propertiesToMatch.putAll(additionalPropertiesToMatch);
+ }
- propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
+ propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid);
- Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
- propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
- Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+ Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
- if (vertexEither.isRight()) {
- log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", componentUuid, vertexEither.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
- }
- List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
+ if (vertexEither.isRight()) {
+ log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", componentUuid, vertexEither.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value()));
+ }
+ List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null;
- if (vertexList == null || vertexList.isEmpty()) {
- log.debug("Component with uuid {} was not found", componentUuid);
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
+ if (vertexList == null || vertexList.isEmpty()) {
+ log.debug("Component with uuid {} was not found", componentUuid);
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
ArrayList<Component> latestComponents = new ArrayList<>();
- for (GraphVertex vertex : vertexList) {
+ for (GraphVertex vertex : vertexList) {
Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex);
if(toscaElementByOperation.isRight()){
@@ -1599,577 +1569,606 @@ public class ToscaOperationFacade {
return Either.left(highestComponent);
}
}
- }
+ }
- return Either.left(latestComponents);
- }
-
- public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
-
- Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid);
-
- if (latestVersionListEither.isRight()) {
- return Either.right(latestVersionListEither.right().value());
- }
-
- List<Component> latestVersionList = latestVersionListEither.left().value();
-
- if (latestVersionList.isEmpty()) {
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
-
- return Either.left(component);
- }
-
- public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
-
- List<Resource> resources = new ArrayList<>();
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
- propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
- if (isHighest != null) {
- propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
- }
- propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
- propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
- propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
-
- Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
-
- if (getResourcesRes.isRight()) {
- log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value()));
- }
- List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
- for (GraphVertex resourceV : resourceVerticies) {
- Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
- if (getResourceRes.isRight()) {
- return Either.right(getResourceRes.right().value());
- }
- resources.add(getResourceRes.left().value());
- }
- return Either.left(resources);
- }
-
- public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
- Either<T, StorageOperationStatus> result;
-
- Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
-
- hasProperties.put(GraphPropertyEnum.NAME, name);
- hasProperties.put(GraphPropertyEnum.VERSION, version);
- hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
-
- hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
-
- Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
- if (getResourceRes.isRight()) {
- TitanOperationStatus status = getResourceRes.right().value();
- log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- return result;
- }
- return getToscaElementByOperation(getResourceRes.left().value().get(0));
- }
-
- public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
- return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll);
- }
-
- public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) {
- Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
- props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
- props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- if (componentType != null) {
- props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
- }
- Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
- propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
-
- GraphVertex resourceMetadataData = null;
- List<GraphVertex> resourceMetadataDataList = null;
- Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
- if (byCsar.isRight()) {
- if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
- // Fix Defect DE256036
- if (StringUtils.isEmpty(systemName)) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
- }
-
- props.clear();
- props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
- Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
- if (bySystemname.isRight()) {
- log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
- }
- if (bySystemname.left().value().size() > 2) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- resourceMetadataDataList = bySystemname.left().value();
- if (resourceMetadataDataList.size() == 1) {
- resourceMetadataData = resourceMetadataDataList.get(0);
- } else {
- for (GraphVertex curResource : resourceMetadataDataList) {
- if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
- resourceMetadataData = curResource;
- break;
- }
- }
- }
- if (resourceMetadataData == null) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
- log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
- // correct error will be returned from create flow. with all
- // correct audit records!!!!!
- return Either.right(StorageOperationStatus.NOT_FOUND);
- }
- Either<Resource, StorageOperationStatus> resource = getToscaElement((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 (GraphVertex curResource : resourceMetadataDataList) {
- if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
- resourceMetadataData = curResource;
- break;
- }
- }
- }
- if (resourceMetadataData == null) {
- log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
- return Either.right(StorageOperationStatus.GENERAL_ERROR);
- }
- Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
- return resource;
- }
- return null;
- }
-
- public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
-
- String currentTemplateNameChecked = templateNameExtends;
-
- while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
- Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
-
- if (latestByToscaResourceName.isRight()) {
- return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
- }
-
- Resource value = latestByToscaResourceName.left().value();
-
- if (value.getDerivedFrom() != null) {
- currentTemplateNameChecked = value.getDerivedFrom().get(0);
- } else {
- currentTemplateNameChecked = null;
- }
- }
-
- return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
- }
-
- public Either<List<Component>, StorageOperationStatus> fetchByResourceType(String resourceType) {
-
- Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
- props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
- props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
- Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props);
-
- if (resourcesByTypeEither.isRight()) {
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
- }
-
- List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
- List<Component> components = new ArrayList<>();
-
- for (GraphVertex vertex : vertexList) {
- components.add(getToscaElementByOperation(vertex).left().value());
- }
-
- return Either.left(components);
-
- }
-
- public void commit() {
- titanDao.commit();
- }
-
- public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
- Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
- if (updateDistributionStatus.isRight()) {
- return Either.right(updateDistributionStatus.right().value());
- }
- GraphVertex serviceV = updateDistributionStatus.left().value();
- service.setDistributionStatus(distributionStatus);
- service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
- return Either.left(service);
- }
-
- public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) {
-
- Either<ComponentMetadataData, StorageOperationStatus> result = null;
- GraphVertex serviceVertex;
- Either<GraphVertex, TitanOperationStatus> updateRes = null;
- Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
- if (getRes.isRight()) {
- TitanOperationStatus status = getRes.right().value();
- log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
- }
- if (result == null) {
- serviceVertex = getRes.left().value();
- long lastUpdateDate = System.currentTimeMillis();
- serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
- component.setLastUpdateDate(lastUpdateDate);
- updateRes = titanDao.updateVertex(serviceVertex);
- if (updateRes.isRight()) {
- result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
- }
- }
- if (result == null) {
- result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
- }
- return result;
- }
-
- public TitanDao getTitanDao() {
- return titanDao;
- }
-
- public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
-
- return getServicesWithDistStatus(distStatus, propertiesToMatch);
- }
-
- public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
-
- List<Service> servicesAll = new ArrayList<>();
-
- Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
- Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
-
- if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
- propertiesToMatch.putAll(additionalPropertiesToMatch);
- }
-
- propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
-
- propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
-
- if (distStatus != null && !distStatus.isEmpty()) {
- for (DistributionStatusEnum state : distStatus) {
- propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
- Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
- if (fetchServicesByCriteria.isRight()) {
- return fetchServicesByCriteria;
- } else {
- servicesAll = fetchServicesByCriteria.left().value();
- }
- }
- return Either.left(servicesAll);
- } else {
- return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
- }
- }
-
- // private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
- // Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
- // if (getRes.isRight()) {
- // if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
- // return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
- // }
- // } else {
- // for (GraphVertex vertex : getRes.left().value()) {
- // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
- // if (getServiceRes.isRight()) {
- // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
- // return Either.right(getServiceRes.right().value());
- // } else {
- // servicesAll.add((Service) getToscaElementByOperation(vertex).left().value());
- // }
- // }
- // }
- // return Either.left(servicesAll);
- // }
-
- private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
- Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
- if (getRes.isRight()) {
- if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
- return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
- }
- } else {
- for (GraphVertex vertex : getRes.left().value()) {
- // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
- Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
-
- if (getServiceRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
- return Either.right(getServiceRes.right().value());
- } else {
- servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
- }
- }
- }
- return Either.left(servicesAll);
- }
-
- public void rollback() {
- titanDao.rollback();
- }
-
- public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
- Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
-
- return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
- }
-
- public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
- return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
- }
-
- public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
- return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
- }
-
- public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) {
-
- Either<PropertyDefinition, StorageOperationStatus> result = null;
- Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
- newPropertyDefinition.setName(propertyName);
- newPropertyDefinition.setParentUniqueId(resource.getUniqueId());
- StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
- if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status);
- result = Either.right(status);
- }
- if (result == null) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreProperties(false);
- getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
- if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
- result = Either.right(status);
- }
- }
- if (result == null) {
- PropertyDefinition newProperty = null;
- List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties();
- if (CollectionUtils.isNotEmpty(properties)) {
- Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny();
- if (newPropertyOptional.isPresent()) {
- newProperty = newPropertyOptional.get();
- }
- }
- if (newProperty == null) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- } else {
- result = Either.left(newProperty);
- }
- }
- return result;
- }
-
- public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) {
- return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
- }
-
- public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
- return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
- }
-
- public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
- return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
- }
-
- public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) {
-
- Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
- Either<PropertyDefinition, StorageOperationStatus> result = null;
- StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
- if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status);
- result = Either.right(status);
- }
- if (result == null) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreProperties(false);
- getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
- if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
- result = Either.right(status);
- }
- }
- if (result == null) {
- Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
- if (newProperty.isPresent()) {
- result = Either.left(newProperty.get());
- } else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- }
- }
- return result;
- }
-
- public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
-
- Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
- Either<PropertyDefinition, StorageOperationStatus> result = null;
- if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
- String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
- newAttributeDef.setUniqueId(attUniqueId);
- }
-
- StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
- if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
- result = Either.right(status);
- }
- if (result == null) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreAttributesFrom(false);
- getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
- if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
- result = Either.right(status);
- }
- }
- if (result == null) {
- Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
- if (newAttribute.isPresent()) {
- result = Either.left(newAttribute.get());
- } else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- }
- }
- return result;
- }
-
- public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
-
- Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
- Either<PropertyDefinition, StorageOperationStatus> result = null;
- StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
- if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
- result = Either.right(status);
- }
- if (result == null) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreAttributesFrom(false);
- getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
- if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
- result = Either.right(status);
- }
- }
- if (result == null) {
- Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
- if (newProperty.isPresent()) {
- result = Either.left(newProperty.get());
- } else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- }
- }
- return result;
- }
-
- public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
-
- Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
- Either<InputDefinition, StorageOperationStatus> result = null;
- StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
- if (status != StorageOperationStatus.OK) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
- result = Either.right(status);
- }
- if (result == null) {
- ComponentParametersView filter = new ComponentParametersView(true);
- filter.setIgnoreInputs(false);
- getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
- if (getUpdatedComponentRes.isRight()) {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
- result = Either.right(status);
- }
- }
- if (result == null) {
- Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
- if (updatedInput.isPresent()) {
- result = Either.left(updatedInput.get());
- } else {
- CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
- result = Either.right(StorageOperationStatus.NOT_FOUND);
- }
- }
- return result;
- }
-
- public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
- return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
- }
-
- public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> updatedGroups) {
- return groupsOperation.updateGroups(component, componentType, updatedGroups);
- }
-
- public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) {
- return groupsOperation.updateGroupInstances(component, componentType, instanceId, updatedGroupInstances);
- }
-
- public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
- return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
- }
-
- public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
- return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
- }
-
- public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
- return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
- }
-
- public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
- return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
- }
-
- public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
- return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
- }
-
- public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
- return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
- }
-
- public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
- this.nodeTypeOperation = nodeTypeOperation;
- }
-
- public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
- this.topologyTemplateOperation = topologyTemplateOperation;
+ return Either.left(latestComponents);
+ }
+
+ public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) {
+
+ Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid);
+
+ if (latestVersionListEither.isRight()) {
+ return Either.right(latestVersionListEither.right().value());
+ }
+
+ List<Component> latestVersionList = latestVersionListEither.left().value();
+
+ if (latestVersionList.isEmpty()) {
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get();
+
+ return Either.left(component);
+ }
+
+ public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) {
+
+ List<Resource> resources = new ArrayList<>();
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
+ if (isHighest != null) {
+ propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue());
+ }
+ propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+
+ if (getResourcesRes.isRight()) {
+ log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value()));
+ }
+ List<GraphVertex> resourceVerticies = getResourcesRes.left().value();
+ for (GraphVertex resourceV : resourceVerticies) {
+ Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV);
+ if (getResourceRes.isRight()) {
+ return Either.right(getResourceRes.right().value());
+ }
+ resources.add(getResourceRes.left().value());
+ }
+ return Either.left(resources);
+ }
+
+ public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) {
+ Either<T, StorageOperationStatus> result;
+
+ Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
+
+ hasProperties.put(GraphPropertyEnum.NAME, name);
+ hasProperties.put(GraphPropertyEnum.VERSION, version);
+ hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
+ hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
+
+ Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
+ if (getResourceRes.isRight()) {
+ TitanOperationStatus status = getResourceRes.right().value();
+ log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ return result;
+ }
+ return getToscaElementByOperation(getResourceRes.left().value().get(0));
+ }
+
+ public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) {
+ return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll);
+ }
+
+ public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) {
+ Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
+ props.put(GraphPropertyEnum.CSAR_UUID, csarUUID);
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ if (componentType != null) {
+ props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+ }
+ Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class);
+ propsHasNot.put(GraphPropertyEnum.IS_DELETED, true);
+
+ GraphVertex resourceMetadataData = null;
+ List<GraphVertex> resourceMetadataDataList = null;
+ Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata);
+ if (byCsar.isRight()) {
+ if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) {
+ // Fix Defect DE256036
+ if (StringUtils.isEmpty(systemName)) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND));
+ }
+
+ props.clear();
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ props.put(GraphPropertyEnum.SYSTEM_NAME, systemName);
+ Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata);
+ if (bySystemname.isRight()) {
+ log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value()));
+ }
+ if (bySystemname.left().value().size() > 2) {
+ log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size());
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ resourceMetadataDataList = bySystemname.left().value();
+ if (resourceMetadataDataList.size() == 1) {
+ resourceMetadataData = resourceMetadataDataList.get(0);
+ } else {
+ for (GraphVertex curResource : resourceMetadataDataList) {
+ if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
+ resourceMetadataData = curResource;
+ break;
+ }
+ }
+ }
+ if (resourceMetadataData == null) {
+ log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
+ log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
+ // correct error will be returned from create flow. with all
+ // correct audit records!!!!!
+ return Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ Either<Resource, StorageOperationStatus> resource = getToscaElement((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 (GraphVertex curResource : resourceMetadataDataList) {
+ if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) {
+ resourceMetadataData = curResource;
+ break;
+ }
+ }
+ }
+ if (resourceMetadataData == null) {
+ log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions");
+ return Either.right(StorageOperationStatus.GENERAL_ERROR);
+ }
+ Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag);
+ return resource;
+ }
+ return null;
+ }
+
+ public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
+
+ String currentTemplateNameChecked = templateNameExtends;
+
+ while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
+ Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
+
+ if (latestByToscaResourceName.isRight()) {
+ return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value());
+ }
+
+ Resource value = latestByToscaResourceName.left().value();
+
+ if (value.getDerivedFrom() != null) {
+ currentTemplateNameChecked = value.getDerivedFrom().get(0);
+ } else {
+ currentTemplateNameChecked = null;
+ }
+ }
+
+ return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false);
+ }
+
+ public Either<List<Component>, StorageOperationStatus> fetchByResourceType(String resourceType) {
+
+ Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
+ props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType);
+ props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props);
+
+ if (resourcesByTypeEither.isRight()) {
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value()));
+ }
+
+ List<GraphVertex> vertexList = resourcesByTypeEither.left().value();
+ List<Component> components = new ArrayList<>();
+
+ for (GraphVertex vertex : vertexList) {
+ components.add(getToscaElementByOperation(vertex).left().value());
+ }
+
+ return Either.left(components);
+
+ }
+
+ public void commit() {
+ titanDao.commit();
+ }
+
+ public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) {
+ Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus);
+ if (updateDistributionStatus.isRight()) {
+ return Either.right(updateDistributionStatus.right().value());
+ }
+ GraphVertex serviceV = updateDistributionStatus.left().value();
+ service.setDistributionStatus(distributionStatus);
+ service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE));
+ return Either.left(service);
+ }
+
+ public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) {
+
+ Either<ComponentMetadataData, StorageOperationStatus> result = null;
+ GraphVertex serviceVertex;
+ Either<GraphVertex, TitanOperationStatus> updateRes = null;
+ Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
+ if (getRes.isRight()) {
+ TitanOperationStatus status = getRes.right().value();
+ log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status);
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
+ }
+ if (result == null) {
+ serviceVertex = getRes.left().value();
+ long lastUpdateDate = System.currentTimeMillis();
+ serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate);
+ component.setLastUpdateDate(lastUpdateDate);
+ updateRes = titanDao.updateVertex(serviceVertex);
+ if (updateRes.isRight()) {
+ result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value()));
+ }
+ }
+ if (result == null) {
+ result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value()));
+ }
+ return result;
+ }
+
+ public TitanDao getTitanDao() {
+ return titanDao;
+ }
+
+ public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) {
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+
+ return getServicesWithDistStatus(distStatus, propertiesToMatch);
+ }
+
+ public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) {
+
+ List<Service> servicesAll = new ArrayList<>();
+
+ Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+ Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+
+ if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) {
+ propertiesToMatch.putAll(additionalPropertiesToMatch);
+ }
+
+ propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+
+ propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+
+ if (distStatus != null && !distStatus.isEmpty()) {
+ for (DistributionStatusEnum state : distStatus) {
+ propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
+ Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
+ if (fetchServicesByCriteria.isRight()) {
+ return fetchServicesByCriteria;
+ } else {
+ servicesAll = fetchServicesByCriteria.left().value();
+ }
+ }
+ return Either.left(servicesAll);
+ } else {
+ return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
+ }
+ }
+
+ // private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
+ // Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+ // if (getRes.isRight()) {
+ // if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
+ // return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
+ // }
+ // } else {
+ // for (GraphVertex vertex : getRes.left().value()) {
+ // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
+ // if (getServiceRes.isRight()) {
+ // CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
+ // return Either.right(getServiceRes.right().value());
+ // } else {
+ // servicesAll.add((Service) getToscaElementByOperation(vertex).left().value());
+ // }
+ // }
+ // }
+ // return Either.left(servicesAll);
+ // }
+
+ private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
+ Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+ if (getRes.isRight()) {
+ if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value());
+ return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value()));
+ }
+ } else {
+ for (GraphVertex vertex : getRes.left().value()) {
+ // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex);
+ Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
+
+ if (getServiceRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value());
+ return Either.right(getServiceRes.right().value());
+ } else {
+ servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value()));
+ }
+ }
+ }
+ return Either.left(servicesAll);
+ }
+
+ public void rollback() {
+ titanDao.rollback();
+ }
+
+ public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) {
+ Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue())));
+
+ return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts);
+ }
+
+ public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
+ return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId);
+ }
+
+ public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
+ return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances);
+ }
+
+ public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) {
+
+ Either<PropertyDefinition, StorageOperationStatus> result = null;
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ newPropertyDefinition.setName(propertyName);
+ newPropertyDefinition.setParentUniqueId(resource.getUniqueId());
+ StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreProperties(false);
+ getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ PropertyDefinition newProperty = null;
+ List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties();
+ if (CollectionUtils.isNotEmpty(properties)) {
+ Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny();
+ if (newPropertyOptional.isPresent()) {
+ newProperty = newPropertyOptional.get();
+ }
+ }
+ if (newProperty == null) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ } else {
+ result = Either.left(newProperty);
+ }
+ }
+ return result;
+ }
+
+ public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) {
+ return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME);
+ }
+
+ public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) {
+ return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME);
+ }
+
+ public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) {
+ return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME);
+ }
+
+ public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) {
+
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ Either<PropertyDefinition, StorageOperationStatus> result = null;
+ StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreProperties(false);
+ getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny();
+ if (newProperty.isPresent()) {
+ result = Either.left(newProperty.get());
+ } else {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ return result;
+ }
+
+ public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
+
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ Either<PropertyDefinition, StorageOperationStatus> result = null;
+ if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) {
+ String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName());
+ newAttributeDef.setUniqueId(attUniqueId);
+ }
+
+ StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreAttributesFrom(false);
+ getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
+ if (newAttribute.isPresent()) {
+ result = Either.left(newAttribute.get());
+ } else {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ return result;
+ }
+
+ public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) {
+
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ Either<PropertyDefinition, StorageOperationStatus> result = null;
+ StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreAttributesFrom(false);
+ getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny();
+ if (newProperty.isPresent()) {
+ result = Either.left(newProperty.get());
+ } else {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ return result;
+ }
+
+ public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) {
+
+ Either<Component, StorageOperationStatus> getUpdatedComponentRes = null;
+ Either<InputDefinition, StorageOperationStatus> result = null;
+ StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME);
+ if (status != StorageOperationStatus.OK) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status);
+ result = Either.right(status);
+ }
+ if (result == null) {
+ ComponentParametersView filter = new ComponentParametersView(true);
+ filter.setIgnoreInputs(false);
+ getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter);
+ if (getUpdatedComponentRes.isRight()) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value());
+ result = Either.right(status);
+ }
+ }
+ if (result == null) {
+ Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny();
+ if (updatedInput.isPresent()) {
+ result = Either.left(updatedInput.get());
+ } else {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND);
+ result = Either.right(StorageOperationStatus.NOT_FOUND);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * method - ename the group instances after referenced container name renamed
+ * flow - VF rename -(triggers)-> Group rename
+ *
+ * @param containerComponent - container such as service
+ * @param componentInstance - context component
+ * @param componentInstanceId - id
+ *
+ * @return - successfull/failed status
+ * **/
+ public Either<StorageOperationStatus,StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId){
+ String uniqueId = componentInstance.getUniqueId();
+ StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockToToscaElement( containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId );
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status);
+ return Either.right(status);
+ }
+ status = addGroupInstancesToComponentInstance( containerComponent , componentInstance, componentInstance.getGroupInstances() );
+ if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
+ CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status);
+ return Either.right(status);
+ }
+ return Either.left(status);
+ }
+
+ public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
+ return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts);
+ }
+
+ public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> updatedGroups) {
+ return groupsOperation.updateGroups(component, componentType, updatedGroups);
+ }
+
+ public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) {
+ return groupsOperation.updateGroupInstances(component, componentType, instanceId, updatedGroupInstances);
+ }
+
+ public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
+ return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances);
+ }
+
+ public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
+ return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts);
+ }
+
+ public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
+ return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
+ }
+
+ public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
+ return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property);
+ }
+
+ public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
+ return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property);
+ }
+
+ public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
+ return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property);
+ }
+
+ public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) {
+ this.nodeTypeOperation = nodeTypeOperation;
+ }
+
+ public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) {
+ this.topologyTemplateOperation = topologyTemplateOperation;
+ }
+
+ public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, ComponentTypeEnum componentType, List<InputDefinition> inputsToDelete) {
+ return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(i -> i.getName()).collect(Collectors.toList()));
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java
index 0ac5a8dbe4..03a5f41d55 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java
@@ -117,8 +117,8 @@ public class ModelConverter {
return vertexType;
}
- private static boolean isAtomicComponent(ResourceTypeEnum resourceType) {
- if (resourceType == null || resourceType == ResourceTypeEnum.VF)
+ public static boolean isAtomicComponent(ResourceTypeEnum resourceType) {
+ if (resourceType == null || resourceType == ResourceTypeEnum.VF || resourceType == ResourceTypeEnum.PNF || resourceType == ResourceTypeEnum.CVFC)
return false;
return true;
}
@@ -302,7 +302,7 @@ public class ModelConverter {
relationshipPair.setId(relation.getUniqueId());
relationshipPair.setCapabilityOwnerId(relation.getCapabilityOwnerId());
- relationshipPair.setCapabilityUid(relation.getCapabiltyId());
+ relationshipPair.setCapabilityUid(relation.getCapabilityId());
relationshipPair.setRequirementOwnerId(relation.getRequirementOwnerId());
relationshipPair.setRequirementUid(relation.getRequirementId());
relationshipPair.setRequirement(relation.getRequirement());
@@ -326,7 +326,7 @@ public class ModelConverter {
requirementCapabilityRelDef.setToId(relation.getToNode());
requirementCapabilityRelDef.setUniqueId(p.getId());
requirementCapabilityRelDef.setCapabilityOwnerId(p.getCapabilityOwnerId());
- requirementCapabilityRelDef.setCapabiltyId(p.getCapabilityUid());
+ requirementCapabilityRelDef.setCapabilityId(p.getCapabilityUid());
requirementCapabilityRelDef.setRequirementOwnerId(p.getRequirementOwnerId());
requirementCapabilityRelDef.setRequirementId(p.getRequirementUid());
requirementCapabilityRelDef.setRequirement(p.getRequirement());
@@ -518,6 +518,24 @@ public class ModelConverter {
resource.setToscaResourceName((String) toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
resource.setVendorName((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_NAME));
resource.setVendorRelease((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_RELEASE));
+ // field isn't mandatory , but shouldn't be null(should be an empty string instead)
+ if (((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)) != null){
+ resource.setResourceVendorModelNumber(((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)));
+ } else {
+ resource.setResourceVendorModelNumber("");
+ }
+ } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) {
+ Service service = (Service) component;
+ if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)) != null){
+ service.setServiceType(((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)));
+ } else {
+ service.setServiceType("");
+ }
+ if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)) != null){
+ service.setServiceRole(((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)));
+ } else {
+ service.setServiceRole("");
+ }
}
component.setConformanceLevel((String) toscaElement.getMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL));
component.setIcon((String) toscaElement.getMetadataValue(JsonPresentationFields.ICON));
@@ -945,6 +963,24 @@ public class ModelConverter {
toscaElement.setMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME, ((Resource) component).getToscaResourceName());
toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_NAME, ((Resource) component).getVendorName());
toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_RELEASE, ((Resource) component).getVendorRelease());
+ // field isn't mandatory , but shouldn't be null(should be an empty string instead)
+ if (((Resource) component).getResourceVendorModelNumber() != null){
+ toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ((Resource) component).getResourceVendorModelNumber());
+ } else {
+ toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, "");
+ }
+ } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) {
+ // field isn't mandatory , but shouldn't be null(should be an empty string instead)
+ if (((Service) component).getServiceType() != null){
+ toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, ((Service) component).getServiceType());
+ } else {
+ toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, "");
+ }
+ if (((Service) component).getServiceRole() != null){
+ toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ((Service) component).getServiceRole());
+ } else {
+ toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, "");
+ }
}
toscaElement.setMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL, component.getConformanceLevel());
toscaElement.setMetadataValue(JsonPresentationFields.IS_DELETED, component.getIsDeleted());
@@ -955,7 +991,7 @@ public class ModelConverter {
toscaElement.setMetadataValue(JsonPresentationFields.CONTACT_ID, component.getContactId());
}
- private static boolean isAtomicComponent(Component component) {
+ public static boolean isAtomicComponent(Component component) {
ComponentTypeEnum componentType = component.getComponentType();
if (!componentType.equals(ComponentTypeEnum.RESOURCE)) {
return false;
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
index f08c52e0fa..51f21ce5b8 100644
--- 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
@@ -24,10 +24,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
-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.User;
+import org.openecomp.sdc.be.model.*;
import fj.data.Either;
@@ -41,6 +38,8 @@ public interface IServiceOperation extends IComponentOperation {
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);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java
index 2847367999..f0e4056663 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java
@@ -39,7 +39,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.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.IComplexDefaultValue;
import org.openecomp.sdc.be.model.PropertyConstraint;
@@ -50,8 +49,6 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter;
import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter;
import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator;
-import org.openecomp.sdc.be.resources.data.CapabilityInstData;
-import org.openecomp.sdc.be.resources.data.PropertyValueData;
import org.openecomp.sdc.be.resources.data.ResourceMetadataData;
import org.openecomp.sdc.be.resources.data.UniqueIdData;
import org.slf4j.Logger;
@@ -118,6 +115,7 @@ public abstract class AbstractOperation {
log.debug("Before adding {} to graph. data = {}", defName, someData);
+ @SuppressWarnings("unchecked")
Either<TitanVertex, TitanOperationStatus> eitherSomeData = titanGenericDao.createNode(someData);
log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData);
@@ -329,7 +327,7 @@ public abstract class AbstractOperation {
value = jsonElement.toString();
}
- return value;
+ return value;
}
protected Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) {
@@ -368,7 +366,7 @@ public abstract class AbstractOperation {
public List<PropertyConstraint> convertConstraints(List<String> constraints) {
- if (constraints == null || constraints.size() == 0) {
+ if (constraints == null || constraints.isEmpty()) {
return null;
}
@@ -378,7 +376,6 @@ public abstract class AbstractOperation {
Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
return constraints.stream().map(c -> gson.fromJson(c, PropertyConstraint.class)).collect(Collectors.toList());
-
}
}
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java
index 43e4d0683b..cb9adeda3f 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
@@ -710,6 +710,13 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo
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:
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
index e06649bf77..9d9814efcb 100644
--- 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
@@ -1963,6 +1963,7 @@ public abstract class ComponentOperation {
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());
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java
index f9057217a6..413ce4c2fa 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java
@@ -155,7 +155,6 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO
@Override
public Either<GroupTypeDefinition, StorageOperationStatus> getGroupType(String uniqueId, boolean inTransaction) {
return getElementType(this::getGroupTypeByUid, uniqueId, inTransaction);
-
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java
index adea89b9ea..70efe12b86 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java
@@ -167,7 +167,6 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp
@Override
public Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyType(String uniqueId, boolean inTransaction) {
return getElementType(this::getPolicyTypeByUid, uniqueId, inTransaction);
-
}
private Either<PolicyTypeDefinition, TitanOperationStatus> getPolicyTypeByUid(String uniqueId) {
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 c40c59facf..0673033546 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
@@ -188,6 +188,9 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T
private Object convertDataTypeToToscaMap(String innerType, Map<String, DataTypeDefinition> dataTypes,
final boolean isScalarF, JsonElement entryValue) {
Object convertedValue;
+ if (entryValue.isJsonPrimitive()) {
+ return json2JavaPrimitive(entryValue.getAsJsonPrimitive());
+ }
JsonObject asJsonObjectIn = entryValue.getAsJsonObject();
DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType);
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java
index 0e7b7f6648..8c63090e03 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatStringValidator.java
@@ -44,8 +44,8 @@ public class HeatStringValidator implements PropertyTypeValidator {
return true;
}
- String coverted = ValidationUtils.removeNoneUtf8Chars(value);
- return ValidationUtils.validateIsEnglish(coverted);
+ String converted = ValidationUtils.removeNoneUtf8Chars(value);
+ return ValidationUtils.validateIsEnglish(converted);
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java
index 4b11e26d05..73b5e939ef 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/KeyValidator.java
@@ -49,8 +49,8 @@ public class KeyValidator implements PropertyTypeValidator {
if (value.length() > STRING_MAXIMUM_LENGTH) {
return false;
}
- String coverted = ValidationUtils.removeNoneUtf8Chars(value);
- return ValidationUtils.validateIsEnglish(coverted);
+ String converted = ValidationUtils.removeNoneUtf8Chars(value);
+ return ValidationUtils.validateIsEnglish(converted);
}
@Override
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java
index 750941cc0b..a096990ad7 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java
@@ -68,8 +68,8 @@ public class StringValidator implements PropertyTypeValidator {
log.debug("parameter String length {} is higher than configured({})", value.length(), STRING_MAXIMUM_LENGTH);
return false;
}
- String coverted = ValidationUtils.removeNoneUtf8Chars(value);
- boolean isValid = ValidationUtils.validateIsAscii(coverted);
+ String converted = ValidationUtils.removeNoneUtf8Chars(value);
+ boolean isValid = ValidationUtils.validateIsAscii(converted);
if (false == isValid && log.isDebugEnabled()) {
log.debug("parameter String value {} is not an ascii string.", value.substring(0, Math.min(value.length(), 20)));
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java
index a2695f8c79..68abb4d749 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java
@@ -29,6 +29,7 @@ public class UiResourceMetadata extends UiComponentMetadata {
private String vendorName;
private String vendorRelease;
+ private String resourceVendorModelNumber;
private ResourceTypeEnum resourceType = ResourceTypeEnum.VFC;
private Boolean isAbstract;
private String cost;
@@ -41,6 +42,7 @@ public class UiResourceMetadata extends UiComponentMetadata {
super(categories, metadata);
this.vendorName = metadata.getVendorName();
this.vendorRelease = metadata.getVendorRelease();
+ this.resourceVendorModelNumber = metadata.getResourceVendorModelNumber();
this.resourceType = metadata.getResourceType();
this.cost = metadata.getCost();
this.licenseType = metadata.getLicenseType();
@@ -75,6 +77,14 @@ public class UiResourceMetadata extends UiComponentMetadata {
public void setVendorRelease(String vendorRelease) {
this.vendorRelease = vendorRelease;
}
+
+ public String getResourceVendorModelNumber() {
+ return resourceVendorModelNumber;
+ }
+
+ public void setResourceVendorModelNumber(String resourceVendorModelNumber) {
+ this.resourceVendorModelNumber = resourceVendorModelNumber;
+ }
public ResourceTypeEnum getResourceType() {
return resourceType;
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java
index 99d586afd2..9a79a26881 100644
--- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java
+++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java
@@ -30,12 +30,16 @@ public class UiServiceMetadata extends UiComponentMetadata {
private String distributionStatus;
private Boolean ecompGeneratedNaming;
private String namingPolicy;
+ private String serviceType;
+ private String serviceRole;
public UiServiceMetadata(List<CategoryDefinition> categories, ServiceMetadataDataDefinition metadata) {
super(categories, metadata);
this.distributionStatus = metadata.getDistributionStatus();
this.ecompGeneratedNaming = metadata.isEcompGeneratedNaming();
this.namingPolicy = metadata.getNamingPolicy();
+ this.serviceType = metadata.getServiceType();
+ this.serviceRole = metadata.getServiceRole();
}
public String getDistributionStatus() {
@@ -61,5 +65,21 @@ public class UiServiceMetadata extends UiComponentMetadata {
public void setNamingPolicy(String namingPolicy) {
this.namingPolicy = namingPolicy;
}
+
+ public String getServiceType() {
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType) {
+ this.serviceType = serviceType;
+ }
+
+ public String getServiceRole() {
+ return serviceRole;
+ }
+
+ public void setServiceRole(String serviceRole) {
+ this.serviceRole = serviceRole;
+ }
}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java
new file mode 100644
index 0000000000..3f80806292
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperationsTest.java
@@ -0,0 +1,85 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import fj.data.Either;
+import org.junit.Test;
+import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
+import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.*;
+
+public class ArtifactsOperationsTest {
+
+ private static final String SERVICE_ID = "serviceId";
+ private static final String INSTANCE_ID = "instanceId";
+ private ArtifactsOperations testInstance = mock(ArtifactsOperations.class, CALLS_REAL_METHODS);
+
+ @Test
+ public void getInstanceArtifacts_collectAllInstanceArtifacts() throws Exception {
+ Map<String, ToscaDataDefinition> instanceArtifacts = Collections.singletonMap(INSTANCE_ID, getArtifactsByInstance("name1"));
+
+ Map<String, ToscaDataDefinition> instanceDeploymentArtifacts = new HashMap<>();
+ instanceDeploymentArtifacts.put(INSTANCE_ID, getArtifactsByInstance("name2", "name3"));
+ instanceDeploymentArtifacts.put("instanceId2", getArtifactsByInstance("name4"));
+
+ doReturn(Either.left(instanceArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ doReturn(Either.left(instanceDeploymentArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID);
+
+ assertTrue(allInstArtifacts.isLeft());
+ assertEquals(allInstArtifacts.left().value().size(), 3);
+ assertTrue(allInstArtifacts.left().value().containsKey("name1"));
+ assertTrue(allInstArtifacts.left().value().containsKey("name2"));
+ assertTrue(allInstArtifacts.left().value().containsKey("name3"));
+ assertFalse(allInstArtifacts.left().value().containsKey("name4"));//this key is of different instance
+ }
+
+ @Test
+ public void getInstanceArtifacts_noArtifactsForInstance() throws Exception {
+ Map<String, ToscaDataDefinition> instanceArtifacts = Collections.singletonMap(INSTANCE_ID, getArtifactsByInstance("name1"));
+
+ doReturn(Either.left(instanceArtifacts)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ doReturn(Either.left(new HashMap<>())).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, "someOtherInstance");
+
+ assertTrue(allInstArtifacts.isLeft());
+ assertTrue(allInstArtifacts.left().value().isEmpty());
+ }
+
+ @Test
+ public void getInstanceArtifacts_errorGettingInstanceArtifacts() throws Exception {
+ doReturn(Either.right(TitanOperationStatus.GENERAL_ERROR)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID);
+ verify(testInstance, times(0)).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ assertTrue(allInstArtifacts.isRight());
+ }
+
+ @Test
+ public void getAllInstanceArtifacts_errorGettingDeploymentArtifacts() throws Exception {
+ doReturn(Either.left(new HashMap<>())).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INSTANCE_ARTIFACTS);
+ doReturn(Either.right(TitanOperationStatus.GENERAL_ERROR)).when(testInstance).getDataFromGraph(SERVICE_ID, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS);
+ Either<Map<String, ArtifactDefinition>, StorageOperationStatus> allInstArtifacts = testInstance.getAllInstanceArtifacts(SERVICE_ID, INSTANCE_ID);
+ assertTrue(allInstArtifacts.isRight());
+ }
+
+ private ToscaDataDefinition getArtifactsByInstance(String ... artifactsNames) {
+ MapArtifactDataDefinition artifactsByInstance = new MapArtifactDataDefinition();
+ Map<String, ArtifactDataDefinition> artifactsByName = new HashMap<>();
+ for (String artifactName : artifactsNames) {
+ artifactsByName.put(artifactName, new ArtifactDataDefinition());
+ }
+ artifactsByInstance.setMapToscaDataDefinition(artifactsByName);
+ return artifactsByInstance;
+ }
+}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java
new file mode 100644
index 0000000000..339023f9a4
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTest.java
@@ -0,0 +1,344 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import fj.data.Either;
+import org.apache.cassandra.cql3.CQL3Type;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestName;
+import org.junit.runner.RunWith;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.ModelTestBase;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.jsontitan.utils.GraphTestUtils;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import java.util.*;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Created by chaya on 6/12/2017.
+ */
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration("classpath:application-context-test.xml")
+public class ToscaElementOperationTest extends ModelTestBase{
+
+ private List<GraphVertex> allVertices = new ArrayList<>();
+ private boolean isInitialized = false;
+
+ @javax.annotation.Resource
+ ToscaElementOperationTestImpl toscaElementOperation;
+
+ @javax.annotation.Resource
+ TitanDao titanDao;
+
+ @BeforeClass
+ public static void initTest(){
+ ModelTestBase.init();
+
+ }
+
+ @Rule
+ public TestName testName = new TestName();
+
+ @Before
+ public void beforeTest() {
+ if (!isInitialized) {
+ GraphTestUtils.clearGraph(titanDao);
+ //exportGraphMl(titanDao.getGraph().left().value(),"");
+ initGraphForTest();
+ isInitialized = true;
+ }
+ }
+
+ @Test
+ public void testGetAllHighestResourcesNoFilter() {
+
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, null, true);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ }
+ }, null);
+ assertEquals(highestResources.stream().count(), highestResourcesExpectedCount);
+ }
+
+ @Test
+ public void testGetAllResourcesCertifiedNoFilter() {
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, null, false);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
+ }, null);
+ highestResourcesExpectedCount += calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ }
+ }, new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
+ });
+ assertEquals(highestResources.stream().count(), highestResourcesExpectedCount);
+ }
+
+ @Test
+ public void testGetHighestResourcesExclude() {
+
+ // exclude VFCMT
+ List<ResourceTypeEnum> excludeList = Arrays.asList(ResourceTypeEnum.VFCMT);
+ assertTrue(genericTestGetResourcesWithExcludeList(excludeList));
+
+ // exclude CP & VL
+ excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP);
+ assertTrue(genericTestGetResourcesWithExcludeList(excludeList));
+
+ // exclude CP & VL & VF & VFC
+ excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP, ResourceTypeEnum.VF, ResourceTypeEnum.VFC);
+ assertTrue(genericTestGetResourcesWithExcludeList(excludeList));
+ }
+
+ @Test
+ public void testGetAllResourcesCertifiedExclude() {
+ // exclude VFCMT
+ List<ResourceTypeEnum> excludeList = Arrays.asList(ResourceTypeEnum.VFCMT);
+ assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList));
+
+ // exclude CP & VL
+ excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP);
+ assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList));
+
+ // exclude CP & VL & VF & VFC
+ excludeList = Arrays.asList(ResourceTypeEnum.VL, ResourceTypeEnum.CP, ResourceTypeEnum.VF, ResourceTypeEnum.VFC);
+ assertTrue(genericTestGetCertifiedResourcesWithExcludeList(excludeList));
+ }
+
+ @Test
+ public void testGetAllHighestServicesNoFilter() {
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, true);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ }
+ }, null);
+ assertEquals(highestResources.stream().count(), highestResourcesExpectedCount);
+ }
+
+ @Test
+ public void testGetAllCertifiedServicesNoFilter() {
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, false);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
+ }, null);
+ highestResourcesExpectedCount += calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ }
+ }, new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
+ });
+ assertEquals(highestResources.stream().count(), highestResourcesExpectedCount);
+ }
+
+ @Test
+ public void testGetServicesExcludeList() {
+ List<ResourceTypeEnum> excludeList = Arrays.asList(ResourceTypeEnum.VF, ResourceTypeEnum.VFCMT);
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, excludeList, true);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ }
+ }, null);
+ assertEquals(highestResources.stream().count(), highestResourcesExpectedCount);
+ }
+
+ @Test
+ public void testGetCertifiedServicesExcludeList() {
+ List<ResourceTypeEnum> excludeList = Arrays.asList(ResourceTypeEnum.VL);
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, excludeList, false);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ }
+ }, null);
+ highestResourcesExpectedCount += calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
+ }, new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ }
+ });
+ assertEquals(highestResources.stream().count(), highestResourcesExpectedCount);
+ }
+
+ private boolean genericTestGetResourcesWithExcludeList(List<ResourceTypeEnum> excludeList) {
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE,excludeList, true);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ }
+ }, new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.RESOURCE_TYPE, excludeList);
+ }
+ });
+ return highestResources.stream().count() == (highestResourcesExpectedCount);
+ }
+
+ private boolean genericTestGetCertifiedResourcesWithExcludeList(List<ResourceTypeEnum> excludeList) {
+ Either<List<ToscaElement>, StorageOperationStatus> highestResourcesRes = toscaElementOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludeList, false);
+ assertTrue(highestResourcesRes.isLeft());
+ List<ToscaElement> highestResources = highestResourcesRes.left().value();
+ // calculate expected count value
+ long highestResourcesExpectedCount = calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
+ }, new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.RESOURCE_TYPE, excludeList);
+ }
+ });
+ highestResourcesExpectedCount += calculateCount(new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ }
+ }, new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ put(GraphPropertyEnum.RESOURCE_TYPE, excludeList);
+ }
+ });
+ return highestResources.stream().count() == highestResourcesExpectedCount;
+ }
+
+ private void initGraphForTest() {
+ Map<GraphPropertyEnum, Object> highstVerticesProps = new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ }
+ };
+
+ Map<GraphPropertyEnum, Object> certifiedVerticesProps = new HashMap<GraphPropertyEnum, Object>() {
+ {
+ put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+ put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
+ }
+ };
+
+ // add vertices with higestVersion = true
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VF));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VFC));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VFCMT));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.VL));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, highstVerticesProps, ResourceTypeEnum.CP));
+ allVertices.add(GraphTestUtils.createServiceVertex(titanDao, highstVerticesProps));
+
+ // add vertices with non-additional properties
+ for (int i=0 ; i<2 ; i++) {
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VF));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VFC));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VFCMT));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.VL));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, new HashMap<>(), ResourceTypeEnum.CP));
+ allVertices.add(GraphTestUtils.createServiceVertex(titanDao, new HashMap<>()));
+ }
+
+ // add certified vertices
+ for (int i=0; i<3; i++) {
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VF));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VFC));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VFCMT));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.VL));
+ allVertices.add(GraphTestUtils.createResourceVertex(titanDao, certifiedVerticesProps, ResourceTypeEnum.CP));
+ allVertices.add(GraphTestUtils.createServiceVertex(titanDao, certifiedVerticesProps));
+ }
+ //allVertices.stream().forEach( v -> System.out.println("type: "+v.getMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE)));
+ //String result = GraphTestUtils.exportGraphMl(titanDao.getGraph().left().value(), "");
+ //System.out.println("graph is: " + result);
+ }
+
+ private long calculateCount(HashMap<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> doesntHaveProps){
+ return allVertices.stream().
+ filter(v -> {
+ Map<GraphPropertyEnum, Object> vertexProps = v.getMetadataProperties();
+ if (hasProps != null) {
+ for (Map.Entry<GraphPropertyEnum, Object> prop: hasProps.entrySet()){
+ Object value = vertexProps.get(prop.getKey());
+ if ( value == null || !value.equals(prop.getValue())) {
+ return false;
+ }
+ }
+ }
+
+ if (doesntHaveProps != null) {
+ for (Map.Entry<GraphPropertyEnum, Object> prop : doesntHaveProps.entrySet()) {
+ Object value = vertexProps.get(prop.getKey());
+ Object propValue = prop.getValue();
+ if ( value != null && propValue != null && propValue instanceof List ) {
+ for (ResourceTypeEnum propVal : (List<ResourceTypeEnum>)propValue) {
+ if (propVal.name().equals(value)) {
+ return false;
+ }
+ }
+ }
+ else if (value != null && value.equals(propValue)){
+ return false;
+ }
+ }
+ }
+ return true;
+ }).count();
+ }
+}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java
new file mode 100644
index 0000000000..27fbce4776
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperationTestImpl.java
@@ -0,0 +1,74 @@
+package org.openecomp.sdc.be.model.jsontitan.operations;
+
+import fj.data.Either;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.ComponentParametersView;
+import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
+import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
+
+/**
+ * Created by cb478c on 6/13/2017.
+ */
+@org.springframework.stereotype.Component("test-tosca-element-operation")
+public class ToscaElementOperationTestImpl extends ToscaElementOperation {
+
+ @Override
+ protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) {
+ titanDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata);
+ T toscaElement = convertToComponent(vertexComponent);
+ return Either.left(toscaElement);
+ }
+
+ @Override
+ public <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView) {
+ return null;
+ }
+
+ @Override
+ public <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView) {
+ return null;
+ }
+
+ @Override
+ public <T extends ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex) {
+ return null;
+ }
+
+ @Override
+ public <T extends ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement) {
+ return null;
+ }
+
+ @Override
+ protected <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) {
+ return null;
+ }
+
+ @Override
+ protected <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) {
+ return null;
+ }
+
+ @Override
+ protected <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) {
+ return null;
+ }
+
+ @Override
+ protected <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) {
+ return null;
+ }
+
+ @Override
+ protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV) {
+ return null;
+ }
+
+ @Override
+ public <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) {
+
+ }
+}
diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java
new file mode 100644
index 0000000000..8e2a283559
--- /dev/null
+++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/GraphTestUtils.java
@@ -0,0 +1,114 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.be.model.jsontitan.utils;
+
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanVertex;
+import fj.data.Either;
+import org.apache.tinkerpop.gremlin.structure.io.IoCore;
+import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
+import org.openecomp.sdc.be.dao.jsongraph.TitanDao;
+import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.UUID;
+
+public final class GraphTestUtils {
+
+ public static GraphVertex createResourceVertex(TitanDao titanDao, Map<GraphPropertyEnum,Object> metadataProps, ResourceTypeEnum type) {
+ GraphVertex vertex = new GraphVertex();
+ if (type == ResourceTypeEnum.VF) {
+ vertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ } else {
+ vertex.setLabel(VertexTypeEnum.NODE_TYPE);
+ vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.NODE_TYPE);
+ }
+ String uuid = UUID.randomUUID().toString();
+ vertex.setUniqueId(uuid);
+
+ vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid);
+ vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name());
+ vertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, type.name());
+ vertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, false);
+ for (Map.Entry<GraphPropertyEnum, Object> prop : metadataProps.entrySet()) {
+ vertex.addMetadataProperty(prop.getKey(), prop.getValue());
+ }
+ titanDao.createVertex(vertex);
+ titanDao.commit();
+ return vertex;
+ }
+
+ public static GraphVertex createServiceVertex(TitanDao titanDao, Map<GraphPropertyEnum, Object> metadataProps){
+ GraphVertex vertex = new GraphVertex(VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ String uuid = UUID.randomUUID().toString();
+ vertex.setUniqueId(uuid);
+ vertex.addMetadataProperty(GraphPropertyEnum.LABEL, VertexTypeEnum.TOPOLOGY_TEMPLATE);
+ vertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uuid);
+ vertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
+ for (Map.Entry<GraphPropertyEnum, Object> prop : metadataProps.entrySet()) {
+ vertex.addMetadataProperty(prop.getKey(), prop.getValue());
+ }
+ titanDao.createVertex(vertex);
+ titanDao.commit();
+ return vertex;
+ }
+
+ public static void clearGraph(TitanDao titanDao) {
+ 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();
+ vertex.remove();
+ }
+ }
+ titanDao.commit();
+ }
+
+ public static String exportGraphMl(TitanGraph graph, String outputDirectory) {
+ String result = null;
+ String outputFile = outputDirectory + File.separator + "exportGraph." + System.currentTimeMillis() + ".graphml";
+ try {
+ try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(outputFile))) {
+ graph.io(IoCore.graphml()).writer().normalize(true).create().writeGraph(os, graph);
+ }
+ result = outputFile;
+ graph.tx().commit();
+ } catch (Exception e) {
+ graph.tx().rollback();
+ e.printStackTrace();
+ }
+ return result;
+ }
+}
diff --git a/catalog-ui/configurations/MenuReadMe.txt b/catalog-ui/configurations/MenuReadMe.txt
index 660427e5c9..16a7d0f0b7 100644
--- a/catalog-ui/configurations/MenuReadMe.txt
+++ b/catalog-ui/configurations/MenuReadMe.txt
@@ -8,8 +8,6 @@ Supported roles:
-----------------------------
ADMIN
DESIGNER
-PRODUCT_STRATEGIST
-PRODUCT_MANAGER
TESTER
OPS
GOVERNOR
diff --git a/catalog-ui/configurations/dev.js b/catalog-ui/configurations/dev.js
index 4058071183..b68842c3fc 100644
--- a/catalog-ui/configurations/dev.js
+++ b/catalog-ui/configurations/dev.js
@@ -55,21 +55,13 @@ const SDC_CONFIG = {
"POST_change_instance_version": "/v1/catalog/:entityType/:entityId/resourceInstance/:id/changeVersion",
"GET_requirements_capabilities": "/v1/catalog/requirmentsCapabilities/:type/:id",
"GET_resource_artifact_types": "/v1/artifactTypes",
- "GET_product_catalog": "/v1/productScreen",
- "GET_product_category": "/v1/productCategories",
- "GET_product_category_temp": "/v1/artifactTypes",
- "POST_product": "/v1/catalog/products/:id/metadata",
- "GET_product_validate_name": "/v1/catalog/services/validate-name/:name",
- "GET_product": "/v1/catalog/products/:id",
- "GET_product_sub_category": "/v1/productSubCategories",
"GET_onboarding": "/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/packages",
"GET_component_from_csar_uuid": "/v1/catalog/resources/csar/:csar_uuid",
"kibana": "/sdc1/kibanaProxy/"
},
"resourceTypesFilter":{
"resource":["CP","VFC","VL"],
- "service":["CP","VF","VL"],
- "product":[]
+ "service":["CP","VF","VL", "PNF","CVFC"]
},
"logConfig": {
"minLogLevel": "debug",
@@ -104,7 +96,7 @@ const SDC_CONFIG = {
"default": "DL-ASDCL1-4ServiceCertificationTeam;DL-ASDCL4-7ServiceCertificationTeam"
}
},
- "roles": ["ADMIN", "TESTER", "GOVERNOR", "OPS", "DESIGNER", "PRODUCT_MANAGER", "PRODUCT_STRATEGIST"],
+ "roles": ["ADMIN", "TESTER", "GOVERNOR", "OPS", "DESIGNER"],
"tutorial": {
"tabs": [
{
@@ -428,4 +420,4 @@ const SDC_CONFIG = {
}
};
-module.exports = SDC_CONFIG; \ No newline at end of file
+module.exports = SDC_CONFIG;
diff --git a/catalog-ui/configurations/menu.js b/catalog-ui/configurations/menu.js
index 12dda2d78b..36f9d8076a 100644
--- a/catalog-ui/configurations/menu.js
+++ b/catalog-ui/configurations/menu.js
@@ -32,8 +32,7 @@ const SDC_MENU_CONFIG = {
"title": "Designer's Workspace",
"pages":[],
"dashboard": {
- "showCreateNew": true,
- "showCreateNewProduct": false
+ "showCreateNew": true
},
"changeLifecycleStateButtons":{
"NOT_CERTIFIED_CHECKOUT":{ "submitForTesting": {"text":"Submit for Testing", "url":"lifecycleState/certificationRequest", "emailModal": "lifecycleState/CERTIFICATIONREQUEST"},
@@ -81,99 +80,11 @@ const SDC_MENU_CONFIG = {
]
},
- "PRODUCT_STRATEGIST":{
- "title": "Product Strategist's Workspace",
- "pages":[],
- "dashboard": {
- "showCreateNew": false,
- "showCreateNewProduct": false
- },
- "changeLifecycleStateButtons":{},
-
- "states":{
- "NOT_CERTIFIED_CHECKOUT":{
- "ANY":[
- ]
- },
- "NOT_CERTIFIED_CHECKIN": {
- "ANY": [
- ]
- },
- "READY_FOR_CERTIFICATION": {
- "ANY":[
- ]
- },
- "CERTIFICATION_IN_PROGRESS":{
- "ANY":[
- ]
- },
- "CERTIFIED":{
- "ANY":[
- ]
- }
- },
- "folder":[
- {"text": "Active Projects", "groupname": "IN_PROGRESS" },
- {"text": "Check Out", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKOUT"},
- {"text": "Check In", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKIN"},
- {"text": "Followed Projects", "groupname": "FOLLOWING" },
- {"text": "Ready For Testing", "group": "FOLLOWING", "state": "READY_FOR_CERTIFICATION"},
- {"text": "In Testing", "group": "FOLLOWING", "state": "CERTIFICATION_IN_PROGRESS"},
- {"text": "Certified", "group": "FOLLOWING", "state": "CERTIFIED"}
- ]
- },
- "PRODUCT_MANAGER":{
- "title": "Product Manager Workspace",
- "pages":[],
- "dashboard": {
- "showCreateNew": false,
- "showCreateNewProduct": true
- },
- "changeLifecycleStateButtons":{
- "NOT_CERTIFIED_CHECKOUT":{ "checkIn": {"text":"Check in", "url":"lifecycleState/CHECKIN", "confirmationModal": "lifecycleState/CHECKIN"},
- "deleteVersion":{"text":"Delete Version", "url":"lifecycleState/UNDOCHECKOUT", "alertModal": "lifecycleState/UNDOCHECKOUT"}
- },
- "NOT_CERTIFIED_CHECKIN":{ "checkOut": {"text":"Check Out", "url":"lifecycleState/CHECKOUT"}
- }
- },
- "states":{
- "NOT_CERTIFIED_CHECKOUT":{
- "ANY":[
- ]
- },
- "NOT_CERTIFIED_CHECKIN": {
- "ANY": [
- ]
- },
- "READY_FOR_CERTIFICATION": {
- "ANY":[
- ]
- },
- "CERTIFICATION_IN_PROGRESS":{
- "ANY":[
- ]
- },
- "CERTIFIED":{
- "ANY":[
- ]
- }
- },
- "folder":[
- {"text": "Active Projects", "groupname": "IN_PROGRESS" },
- {"text": "Check Out", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKOUT"},
- {"text": "Check In", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKIN"},
- {"text": "Followed Projects", "groupname": "FOLLOWING" },
- {"text": "Ready For Testing", "group": "FOLLOWING", "state": "READY_FOR_CERTIFICATION"},
- {"text": "In Testing", "group": "FOLLOWING", "state": "CERTIFICATION_IN_PROGRESS"},
- {"text": "Certified", "group": "FOLLOWING", "state": "CERTIFIED"}
- ]
- },
"TESTER":{
"title": "Tester's Workspace",
"pages":[],
"dashboard": {
- "showCreateNew": false,
- "showCreateNewProduct": false
+ "showCreateNew": false
},
"changeLifecycleStateButtons":{
"READY_FOR_CERTIFICATION":{ "startTesting": {"text":"Start Testing", "url":"lifecycleState/startCertification"}
@@ -208,8 +119,7 @@ const SDC_MENU_CONFIG = {
"title": "Operations Workspace",
"pages":[],
"dashboard": {
- "showCreateNew": false,
- "showCreateNewProduct": false
+ "showCreateNew": false
},
"changeLifecycleStateButtons":{
"DISTRIBUTION_APPROVED":{ "distribute": {"text":"Distribute", "url":"distribution/PROD/activate", "conformanceLevelModal": { "url":"distribution-state/reject", "confirmationModal": "distribution-state/reject" }},
@@ -240,8 +150,7 @@ const SDC_MENU_CONFIG = {
"title": "Governance Rep's Workspace",
"pages":[],
"dashboard": {
- "showCreateNew": false,
- "showCreateNewProduct": false
+ "showCreateNew": false
},
"changeLifecycleStateButtons":{
"DISTRIBUTION_NOT_APPROVED":{ "approve": {"text":"Approve", "url":"distribution-state/approve", "confirmationModal": "distribution-state/approve", "conformanceLevelModal": { "url":"distribution-state/reject", "confirmationModal": "distribution-state/reject" }},
@@ -358,82 +267,6 @@ const SDC_MENU_CONFIG = {
}
},
- "PRODUCT_MANAGER":{
- "states":{
- "NOT_CERTIFIED_CHECKOUT":{
- "ANY":[
- ],
- "NOT_OWNER":[
- ]
- },
- "NOT_CERTIFIED_CHECKIN": {
- "ANY": [
- ]
- },
- "READY_FOR_CERTIFICATION": {
- "ANY":[
- ]
- },
- "CERTIFICATION_IN_PROGRESS":{
- "ANY":[
- ]
- },
- "CERTIFIED":{
- "ANY":[
- ]
- }
- },
- "folder":[
- {"text": "Active Projects", "groupname": "IN_PROGRESS" },
- {"text": "Check Out", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKOUT"},
- {"text": "Check In", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKIN"},
- {"text": "Followed Projects", "groupname": "FOLLOWING" },
- {"text": "Ready For Testing", "group": "FOLLOWING", "state": "READY_FOR_CERTIFICATION"},
- {"text": "In Testing", "group": "FOLLOWING", "state": "CERTIFICATION_IN_PROGRESS"},
- {"text": "Certified", "group": "FOLLOWING", "state": "CERTIFIED"}
- ]
- },
- "PRODUCT_STRATEGIST":{
- "title": "Product Strategist's Workspace",
- "pages":[],
- "dashboard": {
- "showCreateNew": false,
- "showCreateNewProduct": true
- },
- "states":{
- "NOT_CERTIFIED_CHECKOUT":{
- "ANY":[
- ],
- "NOT_OWNER":[
- ]
- },
- "NOT_CERTIFIED_CHECKIN": {
- "ANY": [
- ]
- },
- "READY_FOR_CERTIFICATION": {
- "ANY":[
- ]
- },
- "CERTIFICATION_IN_PROGRESS":{
- "ANY":[
- ]
- },
- "CERTIFIED":{
- "ANY":[
- ]
- }
- },
- "folder":[
- {"text": "Active Projects", "groupname": "IN_PROGRESS" },
- {"text": "Check Out", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKOUT"},
- {"text": "Check In", "group": "IN_PROGRESS", "state": "NOT_CERTIFIED_CHECKIN"},
- {"text": "Followed Projects", "groupname": "FOLLOWING" },
- {"text": "Ready For Testing", "group": "FOLLOWING", "state": "READY_FOR_CERTIFICATION"},
- {"text": "In Testing", "group": "FOLLOWING", "state": "CERTIFICATION_IN_PROGRESS"},
- {"text": "Certified", "group": "FOLLOWING", "state": "CERTIFIED"}
- ]
- },
"OTHER":{
"states":{
"ANY":{
@@ -465,7 +298,6 @@ const SDC_MENU_CONFIG = {
"component_workspace_menu_option": {
"VFC":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
- {"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
{"text":"Deployment Artifact", "action":"onMenuItemPressed", "state": "workspace.deployment_artifacts"},
{"text":"Information Artifact", "action":"onMenuItemPressed", "state": "workspace.information_artifacts"},
{"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
@@ -476,7 +308,6 @@ const SDC_MENU_CONFIG = {
],
"VL":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
- {"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
{"text":"Deployment Artifact", "action":"onMenuItemPressed", "state": "workspace.deployment_artifacts"},
{"text":"Information Artifact", "action":"onMenuItemPressed", "state": "workspace.information_artifacts"},
{"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
@@ -487,7 +318,6 @@ const SDC_MENU_CONFIG = {
],
"CP":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
- {"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
{"text":"Deployment Artifact", "action":"onMenuItemPressed", "state": "workspace.deployment_artifacts"},
{"text":"Information Artifact", "action":"onMenuItemPressed", "state": "workspace.information_artifacts"},
{"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
@@ -498,7 +328,6 @@ const SDC_MENU_CONFIG = {
],
"VF":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
- {"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
{"text":"Deployment Artifact", "action":"onMenuItemPressed", "state": "workspace.deployment_artifacts"},
{"text":"Information Artifact", "action":"onMenuItemPressed", "state": "workspace.information_artifacts"},
{"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
@@ -509,24 +338,25 @@ const SDC_MENU_CONFIG = {
// {"text":"Inputs", "action":"onMenuItemPressed", "state": "workspace.resource_inputs"},
{"text":"Properties Assignment", "action":"onMenuItemPressed", "state": "workspace.properties_assignment"}
],
+ "PNF":[
+ {"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
+ {"text":"Information Artifact", "action":"onMenuItemPressed", "state": "workspace.information_artifacts"},
+ {"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
+ {"text":"Composition", "action":"onMenuItemPressed", "state": "workspace.composition.details"},
+ {"text":"Activity Log", "action":"onMenuItemPressed", "state": "workspace.activity_log"},
+ {"text":"Properties Assignment", "action":"onMenuItemPressed", "state": "workspace.properties_assignment"}
+ ],
"SERVICE":[
{"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
- {"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
{"text":"TOSCA Artifacts", "action":"onMenuItemPressed", "state": "workspace.tosca_artifacts"},
{"text":"Composition", "action":"onMenuItemPressed", "state": "workspace.composition.details"},
{"text":"Activity Log", "action":"onMenuItemPressed", "state": "workspace.activity_log"},
{"text":"Management Workflow", "action":"onMenuItemPressed", "state": "workspace.management_workflow"},
{"text":"Network Call Flow ", "action":"onMenuItemPressed", "state": "workspace.network_call_flow"},
- {"text":"Monitor ", "action":"onMenuItemPressed", "state": "workspace.distribution", "disabledRoles": ["ADMIN", "TESTER", "GOVERNOR", "DESIGNER", "PRODUCT_MANAGER", "PRODUCT_STRATEGIST"]},
+ {"text":"Monitor ", "action":"onMenuItemPressed", "state": "workspace.distribution", "disabledRoles": ["ADMIN", "TESTER", "GOVERNOR", "DESIGNER"]},
{"text":"Deployment", "action":"onMenuItemPressed", "state": "workspace.deployment"},
// {"text":"Inputs", "action":"onMenuItemPressed", "state": "workspace.service_inputs"},
{"text":"Properties Assignment", "action":"onMenuItemPressed", "state": "workspace.properties_assignment"}
- ],
- "PRODUCT":[
- {"text":"General", "action":"onMenuItemPressed", "state": "workspace.general"},
- {"text":"Hierarchy", "action":"onMenuItemPressed", "state": "workspace.hierarchy"},
- {"text":"Icon", "action":"onMenuItemPressed", "state": "workspace.icons"},
- {"text":"Composition", "action":"onMenuItemPressed", "state": "workspace.composition.details"}
]
}
diff --git a/catalog-ui/configurations/mock.json b/catalog-ui/configurations/mock.json
index 2abcbe0ce2..0ce1fbbb5d 100644
--- a/catalog-ui/configurations/mock.json
+++ b/catalog-ui/configurations/mock.json
@@ -77,20 +77,6 @@
"firstName": "op",
"lastName": "ss",
"xEcompRequestId": "ccccc"
- },
- "product_strategist": {
- "userId": "ps0001",
- "email": "product_strategist@sdc.com",
- "firstName": "Orit",
- "lastName": "Barda",
- "xEcompRequestId": "ccccc"
- },
- "product_manager": {
- "userId": "pm0001",
- "email": "product_manager@sdc.com",
- "firstName": "Orit",
- "lastName": "Barda",
- "xEcompRequestId": "ccccc"
}
},
"statuses": {
diff --git a/catalog-ui/configurations/prod.js b/catalog-ui/configurations/prod.js
index 30cb3f2146..971263b710 100644
--- a/catalog-ui/configurations/prod.js
+++ b/catalog-ui/configurations/prod.js
@@ -55,21 +55,13 @@ const SDC_CONFIG = {
"POST_change_instance_version": "/v1/catalog/:entityType/:entityId/resourceInstance/:id/changeVersion",
"GET_requirements_capabilities": "/v1/catalog/requirmentsCapabilities/:type/:id",
"GET_resource_artifact_types": "/v1/artifactTypes",
- "GET_product_catalog": "/v1/productScreen",
- "GET_product_category": "/v1/productCategories",
- "GET_product_category_temp": "/v1/artifactTypes",
- "POST_product": "/v1/catalog/products/:id/metadata",
- "GET_product_validate_name": "/v1/catalog/services/validate-name/:name",
- "GET_product": "/v1/catalog/products/:id",
- "GET_product_sub_category": "/v1/productSubCategories",
"GET_onboarding": "/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/packages",
"GET_component_from_csar_uuid": "/v1/catalog/resources/csar/:csar_uuid",
"kibana": "/sdc1/kibanaProxy/"
},
"resourceTypesFilter":{
"resource":["CP","VFC","VL"],
- "service":["CP","VF","VL"],
- "product":[]
+ "service":["CP","VF","VL", "PNF","CVFC"]
},
"logConfig": {
"minLogLevel": "debug",
@@ -104,7 +96,7 @@ const SDC_CONFIG = {
"default": "DL-ASDCL1-4ServiceCertificationTeam;DL-ASDCL4-7ServiceCertificationTeam"
}
},
- "roles": ["ADMIN", "TESTER", "GOVERNOR", "OPS", "DESIGNER", "PRODUCT_MANAGER", "PRODUCT_STRATEGIST"],
+ "roles": ["ADMIN", "TESTER", "GOVERNOR", "OPS", "DESIGNER"],
"tutorial": {
"tabs": [
{
@@ -426,7 +418,6 @@ const SDC_CONFIG = {
]
}
-
};
module.exports = SDC_CONFIG;
diff --git a/catalog-ui/pom.xml b/catalog-ui/pom.xml
index 0505d91cba..737ed33a41 100644
--- a/catalog-ui/pom.xml
+++ b/catalog-ui/pom.xml
@@ -47,9 +47,6 @@
</excludes>
<followSymlinks>false</followSymlinks>
</fileset>
- <fileset>
- <directory>${basedir}/node_modules</directory>
- </fileset>
</filesets>
</configuration>
</execution>
@@ -100,11 +97,11 @@
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.4</version>
-
+
<configuration>
<installDirectory>${project.parent.basedir}</installDirectory>
</configuration>
-
+
<executions>
<execution>
<id>install node and npm</id>
@@ -117,7 +114,7 @@
<npmVersion>3.10.10</npmVersion>
</configuration>
</execution>
-
+
<execution>
<id>npm set progress off</id>
<goals>
diff --git a/catalog-ui/src/app/app.ts b/catalog-ui/src/app/app.ts
index 50b99e8ab9..707d7e456e 100644
--- a/catalog-ui/src/app/app.ts
+++ b/catalog-ui/src/app/app.ts
@@ -245,17 +245,6 @@ ng1appModule.config([
data: {unsavedChanges: false, bodyClass: 'general'}
}
);
- //
- $stateProvider.state(
- States.WORKSPACE_ICONS, {
- url: 'icons',
- parent: 'workspace',
- controller: viewModelsModuleName + '.IconsViewModel',
- templateUrl: './view-models/workspace/tabs/icons/icons-view.html',
- data: {unsavedChanges: false, bodyClass: 'icons'}
-
- }
- );
$stateProvider.state(
States.WORKSPACE_ACTIVITY_LOG, {
@@ -280,17 +269,6 @@ ng1appModule.config([
);
$stateProvider.state(
- States.WORKSPACE_HIERARCHY, {
- url: 'hierarchy',
- parent: 'workspace',
- controller: viewModelsModuleName + '.ProductHierarchyViewModel',
- templateUrl: './view-models/workspace/tabs/product-hierarchy/product-hierarchy-view.html',
- data: {unsavedChanges: false}
-
- }
- );
-
- $stateProvider.state(
States.WORKSPACE_INFORMATION_ARTIFACTS, {
url: 'information_artifacts',
parent: 'workspace',
@@ -602,7 +580,7 @@ ng1appModule.value('ValidationPattern', /^[\s\w\&_.:-]{1,1024}$/);
ng1appModule.value('ComponentNameValidationPattern', /^(?=.*[^. ])[\s\w\&_.:-]{1,1024}$/); //DE250513 - same as ValidationPattern above, plus requirement that name not consist of dots and/or spaces alone.
ng1appModule.value('PropertyNameValidationPattern', /^[a-zA-Z0-9_:-]{1,50}$/);// DE210977
ng1appModule.value('TagValidationPattern', /^[\s\w_.-]{1,50}$/);
-ng1appModule.value('VendorValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,25}$/);
+ng1appModule.value('VendorReleaseValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,25}$/);
ng1appModule.value('VendorNameValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,60}$/);
ng1appModule.value('VendorModelNumberValidationPattern', /^[\x20-\x21\x23-\x29\x2B-\x2E\x30-\x39\x3B\x3D\x40-\x5B\x5D-\x7B\x7D-\xFF]{1,65}$/);
ng1appModule.value('ContactIdValidationPattern', /^[\s\w-]{1,50}$/);
@@ -696,7 +674,6 @@ ng1appModule.run([
categoryResourceService.getAllCategories((categories: Categories):void => {
cacheService.set('serviceCategories', categories.serviceCategories);
cacheService.set('resourceCategories', categories.resourceCategories);
- cacheService.set('productCategories', categories.productCategories);
}, onError);
};
diff --git a/catalog-ui/src/app/directives/graphs-v2/common/style/component-instances-nodes-style.ts b/catalog-ui/src/app/directives/graphs-v2/common/style/component-instances-nodes-style.ts
index 0a13ebd799..0dcc93dfa7 100644
--- a/catalog-ui/src/app/directives/graphs-v2/common/style/component-instances-nodes-style.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/common/style/component-instances-nodes-style.ts
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -44,7 +44,8 @@ export class ComponentInstanceNodesStyle {
{
selector: 'node',
css: {
- 'font-family': 'omnes-regular,sans-serif',
+ 'font-family': 'OpenSans-Regular,sans-serif',
+
'font-size': 14,
'events': 'yes',
'text-events': 'yes',
diff --git a/catalog-ui/src/app/directives/graphs-v2/palette/palette.directive.ts b/catalog-ui/src/app/directives/graphs-v2/palette/palette.directive.ts
index f1c3405cfa..f46dc6c939 100644
--- a/catalog-ui/src/app/directives/graphs-v2/palette/palette.directive.ts
+++ b/catalog-ui/src/app/directives/graphs-v2/palette/palette.directive.ts
@@ -17,21 +17,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-
-import {
- Component,
- IAppMenu,
- LeftPanelModel,
- NodesFactory,
- LeftPaletteComponent,
- CompositionCiNodeBase,
- ComponentInstance
-} from "app/models";
+import {Component, IAppMenu, LeftPanelModel, NodesFactory, LeftPaletteComponent, CompositionCiNodeBase, ComponentInstance} from "app/models";
import {CompositionGraphGeneralUtils} from "../composition-graph/utils/composition-graph-general-utils";
import {EventListenerService} from "app/services";
import {ResourceType, GRAPH_EVENTS, EVENTS, ComponentInstanceFactory, ModalsHandler} from "app/utils";
import 'sdc-angular-dragdrop';
import {LeftPaletteLoaderService} from "../../../services/components/utils/composition-left-palette-service";
+import {Resource} from "app/models/components/resource";
+import {ComponentType} from "app/utils/constants";
interface IPaletteScope {
components:Array<LeftPaletteComponent>;
@@ -92,7 +85,7 @@ export class Palette implements ng.IDirective {
el.append(this.nodeHtmlSubstitute);
this.registerEventListenerForLeftPalette(scope);
// this.LeftPaletteLoaderService.loadLeftPanel(scope.currentComponent.componentType);
-
+
this.initComponents(scope);
this.initEvents(scope);
this.initDragEvents(scope);
@@ -103,34 +96,31 @@ export class Palette implements ng.IDirective {
});
};
- private registerEventListenerForLeftPalette = (scope:IPaletteScope):void => {
- if (scope.currentComponent.isResource()) {
- this.EventListenerService.registerObserverCallback(EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT, () => {
- this.updateLeftPanelDisplay(scope);
- });
- }
- if (scope.currentComponent.isService()) {
- this.EventListenerService.registerObserverCallback(EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT, () => {
- this.updateLeftPanelDisplay(scope);
- });
- }
- if (scope.currentComponent.isProduct()) {
- this.EventListenerService.registerObserverCallback(EVENTS.PRODUCT_LEFT_PALETTE_UPDATE_EVENT, () => {
- this.updateLeftPanelDisplay(scope);
- });
+ private getUpdateLeftPaletteEventName = (component:Component):string => {
+ switch (component.componentType) {
+ case ComponentType.SERVICE:
+ return EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT;
+ case ComponentType.RESOURCE:
+ if((<Resource>component).resourceType == ResourceType.PNF){
+ return EVENTS.RESOURCE_PNF_LEFT_PALETTE_UPDATE_EVENT;
+ }else{
+ return EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT;
+ }
+ default:
+ console.log('ERROR: Component type '+ component.componentType + ' is not exists');
}
};
+ private registerEventListenerForLeftPalette = (scope:IPaletteScope):void => {
+ let updateEventName:string = this.getUpdateLeftPaletteEventName(scope.currentComponent);
+ this.EventListenerService.registerObserverCallback(updateEventName, () => {
+ this.updateLeftPanelDisplay(scope);
+ });
+ };
+
private unRegisterEventListenerForLeftPalette = (scope:IPaletteScope):void => {
- if (scope.currentComponent.isResource()) {
- this.EventListenerService.unRegisterObserver(EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT);
- }
- if (scope.currentComponent.isService()) {
- this.EventListenerService.unRegisterObserver(EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT);
- }
- if (scope.currentComponent.isProduct()) {
- this.EventListenerService.unRegisterObserver(EVENTS.PRODUCT_LEFT_PALETTE_UPDATE_EVENT);
- }
+ let updateEventName:string = this.getUpdateLeftPaletteEventName(scope.currentComponent);
+ this.EventListenerService.unRegisterObserver(updateEventName);
};
private leftPanelResourceFilter(resourcesNotAbstract:Array<LeftPaletteComponent>, resourceFilterTypes:Array<string>):Array<LeftPaletteComponent> {
@@ -236,7 +226,7 @@ export class Palette implements ng.IDirective {
private updateLeftPanelDisplay(scope:IPaletteScope) {
let entityType:string = scope.currentComponent.componentType.toLowerCase();
let resourceFilterTypes:Array<string> = this.sdcConfig.resourceTypesFilter[entityType];
- scope.components = this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent.componentType);
+ scope.components = this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent);
scope.model = this.initLeftPanel(scope.components, resourceFilterTypes);
scope.displaySortedCategories = angular.copy(scope.model.sortedCategories);
};
@@ -267,7 +257,7 @@ export class Palette implements ng.IDirective {
return;
}
- let component = _.find(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent.componentType), (componentFullData:LeftPaletteComponent) => {
+ let component = _.find(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent), (componentFullData:LeftPaletteComponent) => {
return displayComponent.uniqueId === componentFullData.uniqueId;
});
this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_START, scope.dragElement, component);
@@ -287,7 +277,7 @@ export class Palette implements ng.IDirective {
this.EventListenerService.notifyObservers(GRAPH_EVENTS.ON_PALETTE_COMPONENT_DRAG_ACTION, event);
};
scope.setElementTemplate = (e) => {
- let dragComponent:LeftPaletteComponent = _.find(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent.componentType),
+ let dragComponent:LeftPaletteComponent = _.find(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(scope.currentComponent),
(fullComponent:LeftPaletteComponent) => {
return (<any>angular.element(e.currentTarget).scope()).component.uniqueId === fullComponent.uniqueId;
});
diff --git a/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.html b/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.html
index 3a4720676c..ec9aaf1f7f 100644
--- a/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.html
+++ b/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.html
@@ -56,7 +56,7 @@
</div>
<div data-ng-if="isSchemaTypeDataType" class="i-sdc-form-item map-item-field">
<label class="i-sdc-form-label">Value</label>
- <fields-structure value-obj-ref="valueObjRef[mapKeys[$index]]"
+ <fields-structure value-obj-ref="valueObjRef[mapKeysStatic[$index]]"
type-name="schemaProperty.type"
parent-form-obj="parentFormObj"
fields-prefix-name="'mapValue'+fieldsPrefixName+''+$index"
diff --git a/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.ts b/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.ts
index a2274654c8..5718cdd9b5 100644
--- a/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.ts
+++ b/catalog-ui/src/app/directives/property-types/type-map/type-map-directive.ts
@@ -33,6 +33,7 @@ export interface ITypeMapScope extends ng.IScope {
isSchemaTypeDataType:boolean;
valueObjRef:any;
mapKeys:Array<string>;//array of map keys
+ mapKeysStatic:Array<string>;
MapKeyValidationPattern:RegExp;
fieldsPrefixName:string;
readOnly:boolean;
@@ -82,6 +83,8 @@ export class TypeMapDirective implements ng.IDirective {
scope.isSchemaTypeDataType = this.DataTypesService.isDataTypeForSchemaType(scope.schemaProperty);
if (scope.valueObjRef) {
scope.mapKeys = Object.keys(scope.valueObjRef);
+ //keeping another copy of the keys, as the mapKeys gets overridden sometimes
+ scope.mapKeysStatic = Object.keys(scope.valueObjRef);
}
});
@@ -91,6 +94,8 @@ export class TypeMapDirective implements ng.IDirective {
scope.valueObjRef = {};
}
scope.mapKeys = Object.keys(scope.valueObjRef);
+ //keeping another copy of the keys, as the mapKeys gets overridden sometimes
+ scope.mapKeysStatic = Object.keys(scope.valueObjRef);
if ($attr.defaultValue) {
scope.mapDefaultValue = JSON.parse($attr.defaultValue);
diff --git a/catalog-ui/src/app/directives/structure-tree/structure-tree-directive.html b/catalog-ui/src/app/directives/structure-tree/structure-tree-directive.html
index 7d8a883b33..706dbefb80 100644
--- a/catalog-ui/src/app/directives/structure-tree/structure-tree-directive.html
+++ b/catalog-ui/src/app/directives/structure-tree/structure-tree-directive.html
@@ -6,7 +6,7 @@
<ul>
<li data-ng-repeat="firstLevelResourcesInstances in structureTree.serviceRoot.resourceInstancesList">
<div class="component-container">
- <div class="small {{firstLevelResourcesInstances.icon}}" ng-class="{'sprite-resource-icons': !component.isProduct(), 'sprite-services-icons': component.isProduct()}">
+ <div class="small sprite-resource-icons {{firstLevelResourcesInstances.icon}}">
<div data-ng-class="{'non-certified':!firstLevelResourcesInstances.certified}"
tooltips tooltip-side="top" tooltip-content="Not certified">
</div>
diff --git a/catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.less b/catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.less
index 942196e663..af24776cd3 100644
--- a/catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.less
+++ b/catalog-ui/src/app/directives/utils/sdc-tags/sdc-tags.less
@@ -1,10 +1,10 @@
.tags-box {
- height: 297px;
+ height: 100px;
.bg_c;
.perfect-scrollbar {
- height: 265px;
+ height: 70px;
}
.new-tag-input {
diff --git a/catalog-ui/src/app/models.ts b/catalog-ui/src/app/models.ts
index c7b7577268..f3eb5d5fa6 100644
--- a/catalog-ui/src/app/models.ts
+++ b/catalog-ui/src/app/models.ts
@@ -35,11 +35,9 @@ export * from './models/category';
export * from './models/comments';
export * from './models/components/component';
export * from './models/components/displayComponent';
-export * from './models/components/product';
export * from './models/components/resource';
export * from './models/components/service';
export * from './models/componentsInstances/componentInstance';
-export * from './models/componentsInstances/productInstance';
export * from './models/componentsInstances/resourceInstance';
export * from './models/componentsInstances/serviceInstance';
export * from './models/csar-component';
@@ -102,7 +100,7 @@ export * from './models/tooltip-data';
export * from './models/user';
export * from './models/validate';
export * from './models/component-metadata';
-
+export * from './models/modal';
export * from './models/button';
export * from './models/filter-properties-assignment-data'
export * from './models/properties-inputs/input-be-model'
diff --git a/catalog-ui/src/app/models/app-config.ts b/catalog-ui/src/app/models/app-config.ts
index ef6c195731..40eb18b8b4 100644
--- a/catalog-ui/src/app/models/app-config.ts
+++ b/catalog-ui/src/app/models/app-config.ts
@@ -54,10 +54,7 @@ export interface IApi {
GET_activity_log:string;
GET_configuration_ui:string;
GET_service:string;
- PUT_product:string;
- GET_product:string;
GET_ecomp_menu_items:string;
- GET_product_validate_name:string;
GET_service_validate_name:string;
GET_service_distributions:string;
GET_service_distributions_components:string;
@@ -85,13 +82,6 @@ export interface IApi {
GET_onboarding:string;
GET_component_from_csar_uuid:string;
kibana:string;
-
- //Added by Ikram -- starts
- GET_product_category:string;
- GET_product_category_temp:string;
- GET_product_sub_category:string;
- //Added by Ikram -- ends
-
}
export interface ILogConfig {
@@ -132,8 +122,6 @@ export interface IConfigRoles {
TESTER:IConfigRole;
OPS:IConfigRole;
GOVERNOR:IConfigRole;
- PRODUCT_MANAGER:IConfigRole;
- PRODUCT_STRATEGIST:IConfigRole;
}
export interface IConfigRole {
diff --git a/catalog-ui/src/app/models/categories.ts b/catalog-ui/src/app/models/categories.ts
index b46c3a6612..0921ca158b 100644
--- a/catalog-ui/src/app/models/categories.ts
+++ b/catalog-ui/src/app/models/categories.ts
@@ -25,6 +25,5 @@ import {IMainCategory} from "./category";
export class Categories {
resourceCategories:Array<IMainCategory>;
- productCategories:Array<IMainCategory>;
serviceCategories:Array<IMainCategory>;
}
diff --git a/catalog-ui/src/app/models/component-metadata.ts b/catalog-ui/src/app/models/component-metadata.ts
index 2501f0bab5..8c6ed5593d 100644
--- a/catalog-ui/src/app/models/component-metadata.ts
+++ b/catalog-ui/src/app/models/component-metadata.ts
@@ -56,12 +56,15 @@ export class ComponentMetadata {
public vendorName:string;
public vendorRelease:string;
public derivedFrom: Array<string>;
+ public resourceVendorModelNumber:string;
//Service only
public projectCode:string;
public distributionStatus:string;
public ecompGeneratedNaming: boolean;
public namingPolicy: string;
+ public serviceType:string;
+ public serviceRole:string;
//backend lifecycleState
@@ -103,6 +106,9 @@ export class ComponentMetadata {
this.ecompGeneratedNaming = response.ecompGeneratedNaming;
this.namingPolicy = response.namingPolicy;
this.derivedFrom = response.derivedFrom;
+ this.resourceVendorModelNumber = response.resourceVendorModelNumber;
+ this.serviceType = response.serviceType;
+ this.serviceRole = response.serviceRole;
return this;
}
diff --git a/catalog-ui/src/app/models/components/component.ts b/catalog-ui/src/app/models/components/component.ts
index 0c47cc4cb2..9b2c942483 100644
--- a/catalog-ui/src/app/models/components/component.ts
+++ b/catalog-ui/src/app/models/components/component.ts
@@ -22,7 +22,7 @@
import {AsdcComment, ArtifactModel, ArtifactGroupModel, IFileDownload, PropertyModel, PropertiesGroup, AttributeModel, AttributesGroup, ComponentInstance,
InputModel, DisplayModule, Module, IValidate, RelationshipModel, IMainCategory, RequirementsGroup, CapabilitiesGroup, AdditionalInformationModel,
- Resource, IAppMenu, Product, Service} from "../../models";
+ Resource, IAppMenu, Service} from "../../models";
import {IComponentService} from "../../services/components/component-service";
import {CommonUtils} from "../../utils/common-utils";
@@ -92,7 +92,6 @@ export interface IComponent {
getComponentSubType():string;
isAlreadyCertified():boolean;
- isProduct():boolean;
isService():boolean;
isResource():boolean;
isComplex():boolean;
@@ -797,10 +796,6 @@ export abstract class Component implements IComponent {
//------------------------------------------ Help Functions ----------------------------------------------------------------//
- public isProduct = ():boolean => {
- return this instanceof Product;
- };
-
public isService = ():boolean => {
return this instanceof Service;
};
diff --git a/catalog-ui/src/app/models/components/displayComponent.ts b/catalog-ui/src/app/models/components/displayComponent.ts
index a5407e6d17..3a9cbfdaf3 100644
--- a/catalog-ui/src/app/models/components/displayComponent.ts
+++ b/catalog-ui/src/app/models/components/displayComponent.ts
@@ -97,9 +97,6 @@ export class LeftPaletteComponent {
case ComponentType.SERVICE:
this.iconClass = "sprite-services-icons " + icon;
break;
- case ComponentType.PRODUCT:
- this.iconClass = "sprite-product-icons " + icon;
- break;
default:
this.iconClass = "sprite-resource-icons " + icon;
}
diff --git a/catalog-ui/src/app/models/components/product.ts b/catalog-ui/src/app/models/components/product.ts
deleted file mode 100644
index dfb429b971..0000000000
--- a/catalog-ui/src/app/models/components/product.ts
+++ /dev/null
@@ -1,125 +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=========================================================
- */
-
-/**
- * Created by obarda on 2/4/2016.
- */
-'use strict';
-import {Component} from "./component";
-import {IProductService} from "../../services/components/product-service";
-import {IGroup, ISubCategory, IMainCategory, ICategoryBase} from "../category";
-import {ComponentMetadata} from "../component-metadata";
-
-export class Product extends Component {
-
- public contacts:Array<string>;
- public componentService:IProductService;
- public fullName:string;
-
- constructor(componentService:IProductService, $q:ng.IQService, component?:Product) {
- super(componentService, $q, component);
-
- if (component) {
- this.fullName = component.fullName;
- this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version;
- this.contacts = component.contacts;
- }
- this.componentService = componentService;
- this.iconSprite = "sprite-product-icons";
- }
-
- public deleteGroup = (uniqueId:string):void => {
- _.forEach(this.categories, (category:IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:ISubCategory) => {
- subcategory.groupings = _.reject(subcategory.groupings, (group:IGroup) => {
- return group.uniqueId === uniqueId;
- });
- if (subcategory.groupings.length == 0) { // if there is no groups, delete the subcategory
- category.subcategories = _.reject(category.subcategories, (subcategoryObj:ISubCategory) => {
- return subcategoryObj.uniqueId === subcategory.uniqueId;
- });
- if (category.subcategories.length == 0) { // if there is no subcategory, delete the category
- this.categories = _.reject(this.categories, (categoryObj:IMainCategory) => {
- return categoryObj.uniqueId === category.uniqueId;
- });
- }
- }
- });
- });
- };
-
- private getCategoryObjectById = (categoriesArray:Array<ICategoryBase>, categoryUniqueId:string):ICategoryBase => {
- let categorySelected = _.find(categoriesArray, (category) => {
- return category.uniqueId === categoryUniqueId;
- });
- return categorySelected;
- };
-
- public addGroup = (category:IMainCategory, subcategory:ISubCategory, group:IGroup):void => {
- if (!this.categories) {
- this.categories = new Array<IMainCategory>();
- }
- let existingCategory:IMainCategory = <IMainCategory>this.getCategoryObjectById(this.categories, category.uniqueId);
- let newGroup = angular.copy(group);
- newGroup.filterTerms = undefined;
- newGroup.isDisabled = undefined;
- if (!existingCategory) {
- let newCategory:IMainCategory = angular.copy(category);
- newCategory.filteredGroup = undefined;
- newCategory.subcategories = [];
- let newSubcategory:ISubCategory = angular.copy(subcategory);
- newSubcategory.groupings = [];
- newSubcategory.groupings.push(newGroup);
- newCategory.subcategories.push(newSubcategory);
- this.categories.push(newCategory);
- }
- else {
- let existingSubcategory:ISubCategory = <ISubCategory> this.getCategoryObjectById(existingCategory.subcategories, subcategory.uniqueId);
- if (!existingSubcategory) {
- let newSubcategory:ISubCategory = angular.copy(subcategory);
- newSubcategory.groupings = [];
- newSubcategory.groupings.push(newGroup);
- existingCategory.subcategories.push(newSubcategory);
-
- } else {
- let existingGroup:IGroup = <IGroup> this.getCategoryObjectById(existingSubcategory.groupings, group.uniqueId);
- if (!existingGroup) {
- existingSubcategory.groupings.push(newGroup);
- }
- }
- }
- };
-
- getTypeUrl():string {
- return 'products/';
- }
-
- public setComponentMetadata(componentMetadata:ComponentMetadata) {
- super.setComponentMetadata(componentMetadata);
- this.setComponentDisplayData();
- };
-
- setComponentDisplayData():void {
- this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version;
- this.iconSprite = "sprite-product-icons";
- }
-}
-
-
diff --git a/catalog-ui/src/app/models/components/resource.ts b/catalog-ui/src/app/models/components/resource.ts
index 9f7a123486..138b413028 100644
--- a/catalog-ui/src/app/models/components/resource.ts
+++ b/catalog-ui/src/app/models/components/resource.ts
@@ -41,6 +41,7 @@ export class Resource extends Component {
public payloadData:string;
public payloadName:string;
public importedFile:FileUploadModel;
+ public resourceVendorModelNumber:string;
// Onboarding parameters
public csarUUID:string;
@@ -59,6 +60,7 @@ export class Resource extends Component {
this.resourceType = component.resourceType;
this.csarUUID = component.csarUUID;
this.csarVersion = component.csarVersion;
+ this.resourceVendorModelNumber = component.resourceVendorModelNumber;
this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version + ' ' + this.resourceType;
if (component.categories && component.categories[0] && component.categories[0].subcategories && component.categories[0].subcategories[0]) {
component.mainCategory = component.categories[0].name;
@@ -80,6 +82,7 @@ export class Resource extends Component {
this.csarUUID = componentMetadata.csarUUID;
this.csarVersion = componentMetadata.csarVersion;
this.derivedFrom = componentMetadata.derivedFrom;
+ this.resourceVendorModelNumber = componentMetadata.resourceVendorModelNumber;
this.setComponentDisplayData();
};
@@ -88,7 +91,7 @@ export class Resource extends Component {
};
public isComplex = ():boolean => {
- return this.resourceType === ResourceType.VF;
+ return this.resourceType === ResourceType.VF || this.resourceType === ResourceType.PNF || this.resourceType === ResourceType.CVFC;
};
public isVl = ():boolean => {
diff --git a/catalog-ui/src/app/models/components/service.ts b/catalog-ui/src/app/models/components/service.ts
index fbe32519c3..90a38e895b 100644
--- a/catalog-ui/src/app/models/components/service.ts
+++ b/catalog-ui/src/app/models/components/service.ts
@@ -34,6 +34,8 @@ export class Service extends Component {
public componentService:IServiceService;
public ecompGeneratedNaming:boolean;
public namingPolicy:string;
+ public serviceType:string;
+ public serviceRole:string;
constructor(componentService:IServiceService, $q:ng.IQService, component?:Service) {
super(componentService, $q, component);
@@ -43,6 +45,8 @@ export class Service extends Component {
this.filterTerm = this.name + ' ' + this.description + ' ' + (this.tags ? this.tags.toString() : '') + ' ' + this.version;
this.ecompGeneratedNaming = component.ecompGeneratedNaming;
this.namingPolicy = component.namingPolicy;
+ this.serviceType = component.serviceType;
+ this.serviceRole = component.serviceRole;
if (component.categories && component.categories[0]) {
this.mainCategory = component.categories[0].name;
this.selectedCategory = this.mainCategory;
@@ -155,6 +159,8 @@ export class Service extends Component {
super.setComponentMetadata(componentMetadata);
this.ecompGeneratedNaming = componentMetadata.ecompGeneratedNaming;
this.namingPolicy = componentMetadata.namingPolicy;
+ this.serviceType = componentMetadata.serviceType;
+ this.serviceRole = componentMetadata.serviceRole;
this.setComponentDisplayData();
}
diff --git a/catalog-ui/src/app/models/componentsInstances/componentInstance.ts b/catalog-ui/src/app/models/componentsInstances/componentInstance.ts
index 726e3382ba..06939a7a9e 100644
--- a/catalog-ui/src/app/models/componentsInstances/componentInstance.ts
+++ b/catalog-ui/src/app/models/componentsInstances/componentInstance.ts
@@ -52,6 +52,7 @@ export class ComponentInstance {
public inputs:Array<InputModel>;
public properties:Array<PropertyModel>;
public groupInstances:Array<Module>;
+ public invariantName:string;
constructor(componentInstance?:ComponentInstance) {
@@ -77,6 +78,7 @@ export class ComponentInstance {
this.customizationUUID = componentInstance.customizationUUID;
this.updatePosition(componentInstance.posX, componentInstance.posY);
this.groupInstances = componentInstance.groupInstances;
+ this.invariantName = componentInstance.invariantName;
}
}
@@ -92,7 +94,7 @@ export class ComponentInstance {
};
public isComplex = () : boolean => {
- return this.originType === ResourceType.VF;
+ return this.originType === ResourceType.VF || this.originType === ResourceType.PNF || this.originType === ResourceType.CVFC ;
}
public setInstanceRC = ():void=> {
diff --git a/catalog-ui/src/app/models/componentsInstances/productInstance.ts b/catalog-ui/src/app/models/componentsInstances/productInstance.ts
deleted file mode 100644
index 91f0999b9a..0000000000
--- a/catalog-ui/src/app/models/componentsInstances/productInstance.ts
+++ /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=========================================================
- */
-
-/**
- * Created by obarda on 2/4/2016.
- */
-'use strict';
-import {ComponentInstance} from "./componentInstance";
-
-export class ProductInstance extends ComponentInstance {
-
- constructor(componentInstance?:ProductInstance) {
- super(componentInstance);
- this.iconSprite = "sprite-product-icons";
- }
-}
diff --git a/catalog-ui/src/app/models/modal.ts b/catalog-ui/src/app/models/modal.ts
new file mode 100644
index 0000000000..51aa5e19a7
--- /dev/null
+++ b/catalog-ui/src/app/models/modal.ts
@@ -0,0 +1,16 @@
+import { ButtonModel } from 'app/models';
+
+export class ModalModel {
+ size: string; 'xl|l|md|sm|xsm'
+ title: string;
+ content: any;
+ buttons: Array<ButtonModel>;
+
+ constructor(size?: string, title?: string, content?: any, buttons?: Array<ButtonModel>) {
+ this.size = size;
+ this.title = title;
+ this.content = content;
+ this.buttons = buttons;
+ }
+}
+
diff --git a/catalog-ui/src/app/models/properties-inputs/input-fe-model.ts b/catalog-ui/src/app/models/properties-inputs/input-fe-model.ts
index 04a224bff7..630374aac3 100644
--- a/catalog-ui/src/app/models/properties-inputs/input-fe-model.ts
+++ b/catalog-ui/src/app/models/properties-inputs/input-fe-model.ts
@@ -40,4 +40,4 @@ export class InputFEModel extends InputBEModel {
}
}
-}
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/models/properties-inputs/property-fe-model.ts b/catalog-ui/src/app/models/properties-inputs/property-fe-model.ts
index 78d01d9af2..b35bb27b65 100644
--- a/catalog-ui/src/app/models/properties-inputs/property-fe-model.ts
+++ b/catalog-ui/src/app/models/properties-inputs/property-fe-model.ts
@@ -55,7 +55,7 @@ export class PropertyFEModel extends PropertyBEModel {
} catch (e){}
}
- return (this.derivedDataType == DerivedPropertyType.SIMPLE) ? this.valueObj : JSON.stringify(this.valueObj);
+ return (this.derivedDataType == DerivedPropertyType.SIMPLE) ? this.valueObj : JSON.stringify(this.valueObj);
}
public setNonDeclared = (childPath?: string): void => {
@@ -101,16 +101,16 @@ export class PropertyFEModel extends PropertyBEModel {
// this.flattenedChildren.filter(prop => prop.parentName == item.parentName).map(prop => prop.propertiesName).indexOf(item.propertiesName)
// }
- /* Updates parent valueObj when a child prop's value has changed */
- public childPropUpdated = (childProp: DerivedFEProperty): void => {
+ /* Updates parent valueObj when a child prop's value has changed */
+ public childPropUpdated = (childProp: DerivedFEProperty): void => {
let parentNames = this.getParentNamesArray(childProp.propertiesName, []);
if (parentNames.length) {
_.set(this.valueObj, parentNames.join('.'), childProp.valueObj);
}
};
- /* Returns array of individual parents for given prop path, with list/map UUIDs replaced with index/mapkey */
- private getParentNamesArray = (parentPropName: string, parentNames?: Array<string>): Array<string> => {
+ /* Returns array of individual parents for given prop path, with list/map UUIDs replaced with index/mapkey */
+ public getParentNamesArray = (parentPropName: string, parentNames?: Array<string>): Array<string> => {
if (parentPropName.indexOf("#") == -1) { return parentNames; } //finished recursing parents. return
let parentProp: DerivedFEProperty = this.flattenedChildren.find(prop => prop.propertiesName === parentPropName);
diff --git a/catalog-ui/src/app/models/user.ts b/catalog-ui/src/app/models/user.ts
index ec42aed553..54ddf1e5f6 100644
--- a/catalog-ui/src/app/models/user.ts
+++ b/catalog-ui/src/app/models/user.ts
@@ -26,9 +26,7 @@ export enum UserRole {
DESIGNER,
TESTER,
GOVERNOR,
- OPS,
- PRODUCT_MANAGER,
- PRODUCT_STRATEGIST
+ OPS
}
export interface IUserManager {
@@ -99,12 +97,6 @@ export class User implements IUser {
case UserRole.OPS:
role = UserRole.OPS;
break;
- case UserRole.PRODUCT_MANAGER:
- role = UserRole.PRODUCT_MANAGER;
- break;
- case UserRole.PRODUCT_STRATEGIST:
- role = UserRole.PRODUCT_STRATEGIST;
- break;
}
return role;
}
diff --git a/catalog-ui/src/app/modules/service-module.ts b/catalog-ui/src/app/modules/service-module.ts
index bf9ebce749..99624ada45 100644
--- a/catalog-ui/src/app/modules/service-module.ts
+++ b/catalog-ui/src/app/modules/service-module.ts
@@ -35,7 +35,6 @@ import {DataTypesService} from "../services/data-types-service";
import {ComponentService} from "../services/components/component-service";
import {ServiceService} from "../services/components/service-service";
import {ResourceService} from "../services/components/resource-service";
-import {ProductService} from "../services/components/product-service";
import {LeftPaletteLoaderService} from "../services/components/utils/composition-left-palette-service";
import {EventListenerService} from "../services/event-listener-service";
import {ProgressService} from "../services/progress-service";
@@ -69,7 +68,6 @@ serviceModule.service('Sdc.Services.DataTypesService', DataTypesService);
serviceModule.service('Sdc.Services.Components.ComponentService', ComponentService);
serviceModule.service('Sdc.Services.Components.ServiceService',ServiceService);
serviceModule.service('Sdc.Services.Components.ResourceService', ResourceService);
-serviceModule.service('Sdc.Services.Components.ProductService', ProductService);
serviceModule.service('LeftPaletteLoaderService', LeftPaletteLoaderService);
serviceModule.service('EventListenerService', EventListenerService);
serviceModule.service('Sdc.Services.ProgressService', ProgressService);
diff --git a/catalog-ui/src/app/modules/view-model-module.ts b/catalog-ui/src/app/modules/view-model-module.ts
index de7bc5ac1f..f94bfc3218 100644
--- a/catalog-ui/src/app/modules/view-model-module.ts
+++ b/catalog-ui/src/app/modules/view-model-module.ts
@@ -56,13 +56,12 @@ import {OnboardingModalViewModel} from "../view-models/modals/onboarding-modal/o
import {DistributionStatusModalViewModel} from "../view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal-view-model";
import {DcaeAppViewModel} from "../view-models/dcae-app/dcae-app-view-model";
import {GeneralViewModel} from "../view-models/workspace/tabs/general/general-view-model";
-import {IconsViewModel} from "../view-models/workspace/tabs/icons/icons-view-model";
+import {IconsModalViewModel} from "../view-models/modals/icons-modal/icons-modal-view";
import {DeploymentArtifactsViewModel} from "../view-models/workspace/tabs/deployment-artifacts/deployment-artifacts-view-model";
import {InformationArtifactsViewModel} from "../view-models/workspace/tabs/information-artifacts/information-artifacts-view-model";
import {ToscaArtifactsViewModel} from "../view-models/workspace/tabs/tosca-artifacts/tosca-artifacts-view-model";
import {PropertiesViewModel} from "../view-models/workspace/tabs/properties/properties-view-model";
import {AttributesViewModel} from "../view-models/workspace/tabs/attributes/attributes-view-model";
-import {ProductHierarchyViewModel} from "../view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model";
import {ActivityLogViewModel} from "../view-models/workspace/tabs/activity-log/activity-log";
import {ManagementWorkflowViewModel} from "../view-models/workspace/tabs/management-workflow/management-workflow-view-model";
import {NetworkCallFlowViewModel} from "../view-models/workspace/tabs/network-call-flow/network-call-flow-view-model";
@@ -114,6 +113,7 @@ viewModelModule
.controller(moduleName + '.UserManagementViewModel', UserManagementViewModel)
.controller(moduleName + '.CategoryManagementViewModel', CategoryManagementViewModel)
.controller(moduleName + '.OnboardingModalViewModel', OnboardingModalViewModel)
+ .controller(moduleName + '.IconsModalViewModel', IconsModalViewModel)
.controller(moduleName + '.DistributionStatusModalViewModel', DistributionStatusModalViewModel)
.controller(moduleName + '.DcaeAppViewModel', DcaeAppViewModel)
//
@@ -122,13 +122,11 @@ viewModelModule
.controller(moduleName + '.ConformanceLevelModalViewModel', ConformanceLevelModalViewModel)
.controller(moduleName + '.CompositionViewModel', CompositionViewModel)
.controller(moduleName + '.GeneralViewModel', GeneralViewModel)
- .controller(moduleName + '.IconsViewModel', IconsViewModel)
.controller(moduleName + '.DeploymentArtifactsViewModel', DeploymentArtifactsViewModel)
.controller(moduleName + '.InformationArtifactsViewModel', InformationArtifactsViewModel)
.controller(moduleName + '.ToscaArtifactsViewModel', ToscaArtifactsViewModel)
.controller(moduleName + '.PropertiesViewModel', PropertiesViewModel)
.controller(moduleName + '.AttributesViewModel', AttributesViewModel)
- .controller(moduleName + '.ProductHierarchyViewModel', ProductHierarchyViewModel)
.controller(moduleName + '.ActivityLogViewModel', ActivityLogViewModel)
.controller(moduleName + '.ManagementWorkflowViewModel', ManagementWorkflowViewModel)
.controller(moduleName + '.NetworkCallFlowViewModel', NetworkCallFlowViewModel)
diff --git a/catalog-ui/src/app/ng2/app.component.ts b/catalog-ui/src/app/ng2/app.component.ts
index 58f483ae11..cb10581c93 100644
--- a/catalog-ui/src/app/ng2/app.component.ts
+++ b/catalog-ui/src/app/ng2/app.component.ts
@@ -18,7 +18,7 @@
* ============LICENSE_END=========================================================
*/
-import { Component, Inject } from '@angular/core';
+import { Component, Inject, ViewContainerRef } from '@angular/core';
import { AuthenticationService } from './services/authentication.service';
@Component({
@@ -28,7 +28,7 @@ import { AuthenticationService } from './services/authentication.service';
})
export class AppComponent {
- constructor(auth:AuthenticationService){
+ constructor(auth:AuthenticationService, public viewContainerRef:ViewContainerRef){
}
diff --git a/catalog-ui/src/app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component.html b/catalog-ui/src/app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component.html
deleted file mode 100644
index 7fdd95b304..0000000000
--- a/catalog-ui/src/app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component.html
+++ /dev/null
@@ -1,3 +0,0 @@
-<modal #confirmationModal title="Delete Input" size="sm" [buttons]="footerButtons">
- Are you sure you want to delete this input?
-</modal>
diff --git a/catalog-ui/src/app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component.ts b/catalog-ui/src/app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component.ts
deleted file mode 100644
index f73692f525..0000000000
--- a/catalog-ui/src/app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component.ts
+++ /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=========================================================
- */
-
-/**
- * Created by rc2122 on 6/1/2017.
- */
-import {Component, Output, EventEmitter, ViewChild} from "@angular/core";
-import {ButtonsModelMap, ButtonModel} from "app/models/button";
-import {ModalComponent} from "app/ng2/components/modal/modal.component";
-
-@Component({
- selector: 'confirm-delete-input',
- templateUrl: './confirmation-delete-input.component.html'
-})
-export class ConfirmationDeleteInputComponent {
-
- @Output() deleteInput: EventEmitter<any> = new EventEmitter<any>();
- @ViewChild ('confirmationModal') confirmationModal:ModalComponent;
- footerButtons:ButtonsModelMap = {};
-
- constructor (){
- }
-
- ngOnInit() {
- this.footerButtons['Delete'] = new ButtonModel('Delete', 'blue', this.onDeleteInput);
- this.footerButtons['Close'] = new ButtonModel('Close', 'grey', this.closeModal);
- }
-
- onDeleteInput = (input) => {
- this.deleteInput.emit(input);
- this.closeModal();
- };
-
- openModal = () => {
- this.confirmationModal.open();
- }
-
- closeModal = () => {
- this.confirmationModal.close();
- }
-}
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 331415c26f..38de3ce649 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
@@ -45,6 +45,5 @@
</div>
</div>
</div>
-<confirm-delete-input #deleteInputConfirmation (deleteInput)="onDeleteInput()"></confirm-delete-input>
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 526f5de360..30cdb89d8e 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
@@ -23,7 +23,9 @@
*/
import {Component, Input, Output, EventEmitter, ViewChild} from "@angular/core";
import {InputFEModel} from "app/models";
-import {ConfirmationDeleteInputComponent} from "./confirmation-delete-input/confirmation-delete-input.component";
+import { ModalService } from 'app/ng2/services/modal.service';
+
+
@Component({
selector: 'inputs-table',
@@ -38,11 +40,10 @@ export class InputsTableComponent {
@Input() isLoading:boolean;
@Output() inputValueChanged: EventEmitter<any> = new EventEmitter<any>();
@Output() deleteInput: EventEmitter<any> = new EventEmitter<any>();
- @ViewChild ('deleteInputConfirmation') deleteInputConfirmation:ConfirmationDeleteInputComponent;
selectedInputToDelete:InputFEModel;
- constructor (){
+ constructor(private modalService: ModalService){
}
onInputValueChanged = (input) => {
@@ -51,11 +52,12 @@ export class InputsTableComponent {
onDeleteInput = () => {
this.deleteInput.emit(this.selectedInputToDelete);
+ this.modalService.closeCurrentModal();
};
openDeleteModal = (input:InputFEModel) => {
this.selectedInputToDelete = input;
- this.deleteInputConfirmation.openModal();
+ this.modalService.openActionModal("Delete Input", "Are you sure you want to delete this input?", "Delete", this.onDeleteInput, "Close");
}
}
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 4882449596..cc411bc751 100644
--- a/catalog-ui/src/app/ng2/components/modal/modal.component.html
+++ b/catalog-ui/src/app/ng2/components/modal/modal.component.html
@@ -1,17 +1,15 @@
-<div class="custom-modal {{size}}">
+<div class="custom-modal {{input.size}}">
<div class="ng2-modal-content">
<div class="ng2-modal-header">
- <span class="title">{{ title }}</span>
+ <span class="title">{{ input.title }}</span>
<span class="close-button" (click)="close()"></span>
</div>
- <div class="ng2-modal-body">
- <ng-content></ng-content>
- </div>
+ <div class="ng2-modal-body" >{{input.content}}</div>
<div class="ng2-modal-footer">
- <button *ngFor="let buttonName of buttonsNames"
- class="tlv-btn {{buttons[buttonName].cssClass}}"
- [disabled] = "buttons[buttonName].getDisabled && buttons[buttonName].getDisabled()"
- (click) = "buttons[buttonName].callback()">{{buttons[buttonName].text}}</button>
+ <button *ngFor="let button of input.buttons"
+ class="tlv-btn {{button.cssClass}}"
+ [disabled] = "button.getDisabled && button.getDisabled()"
+ (click) = "button.callback()">{{button.text}}</button>
</div>
</div>
</div>
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 e432a6fde0..09fb9abdd1 100644
--- a/catalog-ui/src/app/ng2/components/modal/modal.component.ts
+++ b/catalog-ui/src/app/ng2/components/modal/modal.component.ts
@@ -22,8 +22,9 @@
* Created by rc2122 on 6/1/2017.
*/
import { Component, ElementRef, Input, OnInit, OnDestroy } from '@angular/core';
+//import {ViewContainerRef, ViewChild} from '@angular/core';
import * as $ from 'jquery';
-import {ButtonsModelMap} from "app/models/button";
+import { ButtonsModelMap, ModalModel } from 'app/models';
@Component({
selector: 'modal',
@@ -32,22 +33,17 @@ import {ButtonsModelMap} from "app/models/button";
})
export class ModalComponent implements OnInit, OnDestroy {
- @Input() size: string; 'xl|l|md|sm|xsm'
- @Input() title: string;
- @Input() public buttons:ButtonsModelMap;
+ @Input() input: ModalModel;
private modalElement: JQuery;
- private buttonsNames:Array<string>;
+ //@ViewChild('modalBody', { read: ViewContainerRef }) modalContainer: ViewContainerRef; //TODO: allow for custom component as body instead of simple message
+
constructor( el: ElementRef ) {
this.modalElement = $(el.nativeElement);
}
ngOnInit(): void {
- let modal = this;
this.modalElement.appendTo('body');
- if(this.buttons){
- this.buttonsNames = Object.keys(this.buttons);
- }
}
ngOnDestroy(): void {
diff --git a/catalog-ui/src/app/ng2/components/modal/modal.module.ts b/catalog-ui/src/app/ng2/components/modal/modal.module.ts
new file mode 100644
index 0000000000..d77be2cd23
--- /dev/null
+++ b/catalog-ui/src/app/ng2/components/modal/modal.module.ts
@@ -0,0 +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"
+
+@NgModule({
+ declarations: [
+ ModalComponent,
+ ],
+ imports: [CommonModule],
+ exports: [],
+ entryComponents: [
+ ModalComponent
+ ],
+ providers: [ModalService]
+})
+export class ModalModule {
+
+} \ No newline at end of file
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 92948b3b0d..95cc79dce9 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
@@ -5,12 +5,12 @@
<!-- LEFT CELL -->
<ng-container *ngIf="!isPropertyFEModel">
<div class="table-cell" *ngIf="canBeDeclared" [ngClass]="{'filtered':property.name === propertyNameSearchText}" [class.round-checkbox]="property.isDeclared"> <!-- simple children of complex type [@checkEffect]="property.isDeclared"-->
- <checkbox [(checked)]="property.isSelected" [disabled]="property.isDisabled ||property.isDeclared || readonly" (checkedChange)="checkProperty.emit(property.propertiesName)" ></checkbox>
+ <checkbox [(checked)]="property.isSelected" [disabled]="property.isDisabled ||property.isDeclared || readonly" (checkedChange)="checkProperty.emit(property.propertiesName)" ></checkbox>
<div class="inner-cell-div" tooltip="{{property.name}}"><span>{{property.name}}</span></div>
</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.value)" [readonly]="readonly" type="text" [ngClass]="{'disabled':readonly}" />
+ <input [value]="property.mapKey" #mapKey (change)="mapKeyChanged.emit(mapKey)" [readonly]="readonly" type="text" [ngClass]="{'disabled':readonly, 'error':!mapKey.validity.valid}" />
</div>
</ng-container>
<!-- RIGHT CELL OR FULL WIDTH CELL-->
@@ -36,7 +36,7 @@
</ng-container>
<!-- ICONS: add, delete, and expand -->
<ng-container *ngIf="!property.isDeclared">
- <a *ngIf="(propType == derivedPropertyTypes.LIST || propType == derivedPropertyTypes.MAP) && !property.isChildOfListOrMap" class="property-icon add-item" (click)="createNewChildProperty();" [ngClass]="{'disabled':readonly}">Add value to list</a>
+ <a *ngIf="(propType == derivedPropertyTypes.LIST || propType == derivedPropertyTypes.MAP) && !property.isChildOfListOrMap" class="property-icon add-item" (click)="createNewChildProperty();" [ngClass]="{'disabled':readonly || preventInsertItem(property)}">Add value to list</a>
<span *ngIf="property.isChildOfListOrMap" (click)="deleteItem.emit(property);" class="property-icon sprite-new delete-item-icon" [ngClass]="{'disabled':readonly}"></span>
<span *ngIf="!isPropertyFEModel && (propType == derivedPropertyTypes.COMPLEX || ((propType == derivedPropertyTypes.LIST || propType == derivedPropertyTypes.MAP) && hasChildren()))" (click)="expandChildById(propPath)" class="property-icon sprite-new round-expand-icon" [class.open]="expandedChildId.indexOf(propPath) == 0"></span>
</ng-container>
diff --git a/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.less b/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.less
index 4da98ec736..48d3d035d0 100644
--- a/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.less
+++ b/catalog-ui/src/app/ng2/components/properties-table/dynamic-property/dynamic-property.component.less
@@ -1,3 +1,4 @@
+@import '../../../../../assets/styles/variables.less';
.flat-children-container {
.dynamic-property-row {
/*create nested left border classes for up to 10 levels of nesting*/
@@ -64,4 +65,10 @@
overflow: hidden;
display: inline;
padding-left: 8px;
-} \ No newline at end of file
+}
+.error {
+ border: solid 1px @func_color_q;
+ color: @func_color_q;
+ outline: none;
+ box-sizing: border-box;
+}
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 e078b74d65..59811b582d 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
@@ -88,7 +88,7 @@ export class DynamicPropertyComponent {
}
createNewChildProperty = (): void => {
-
+
let newProps: Array<DerivedFEProperty> = this.propertiesUtils.createListOrMapChildren(this.property, "", undefined);
if (this.property instanceof PropertyFEModel) {
this.addChildProps(newProps, this.property.name);
@@ -98,11 +98,22 @@ export class DynamicPropertyComponent {
}
addChildProps = (newProps: Array<DerivedFEProperty>, childPropName: string) => {
-
+
if (this.property instanceof PropertyFEModel) {
- let insertIndex: number = this.property.getIndexOfChild(childPropName) + this.property.getCountOfChildren(childPropName); //insert after parent prop and existing children
- this.property.flattenedChildren.splice(insertIndex, 0, ...newProps); //using ES6 spread operator
+ let insertIndex: number = this.property.getIndexOfChild(childPropName) + this.property.getCountOfChildren(childPropName); //insert after parent prop and existing children
+ this.property.flattenedChildren.splice(insertIndex, 0, ...newProps); //using ES6 spread operator
this.expandChildById(newProps[0].propertiesName);
+
+
+ if(!newProps[0].schema.property.isSimpleType){
+ angular.forEach(newProps, (prop:DerivedFEProperty):void => { //Update parent PropertyFEModel with value for each child, including nested props
+ (<PropertyFEModel>this.property).childPropUpdated(prop);
+ },this);
+ //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);
+ }
}
}
@@ -113,7 +124,7 @@ export class DynamicPropertyComponent {
this.dataTypeService.checkForCustomBehavior(this.property);
this.valueChanged.emit(this.property.name);
}
- }
+ }
deleteListOrMapItem = (item: DerivedFEProperty) => {
if (this.property instanceof PropertyFEModel) {
@@ -123,15 +134,22 @@ export class DynamicPropertyComponent {
}
}
- removeValueFromParent = (item: DerivedFEProperty, replaceKey?: string) => {
+ removeValueFromParent = (item: DerivedFEProperty, target?: any) => {
if (this.property instanceof PropertyFEModel) {
let itemParent = (item.parentName == this.property.name) ? this.property : this.property.flattenedChildren.find(prop => prop.propertiesName == item.parentName);
if (item.derivedDataType == DerivedPropertyType.MAP) {
let oldKey = item.mapKey;
- if (typeof replaceKey == 'string') { //allow saving empty string
- _.set(itemParent.valueObj, replaceKey, itemParent.valueObj[oldKey]);
- item.mapKey = replaceKey;
+ if (target && typeof target.value == 'string') { //allow saving empty string
+ let replaceKey:string = target.value;
+ if(Object.keys(itemParent.valueObj).indexOf(replaceKey) > -1){//the key is exists
+ target.setCustomValidity('This key is already exists.');
+ return;
+ }else {
+ target.setCustomValidity('');
+ _.set(itemParent.valueObj, replaceKey, itemParent.valueObj[oldKey]);
+ item.mapKey = replaceKey;
+ }
}
delete itemParent.valueObj[oldKey];
} else {
@@ -147,4 +165,11 @@ export class DynamicPropertyComponent {
}
}
+ preventInsertItem = (property:DerivedFEProperty):boolean => {
+ if(property.type == PROPERTY_TYPES.MAP && Object.keys(property.valueObj).indexOf('') > -1 ){
+ return true;
+ }
+ return false;
+ }
+
}
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 1e09c9e4c6..3a5daba711 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
@@ -37,14 +37,13 @@ import { HierarchyNavService } from './../../services/hierarchy-nav.service';
import { PropertiesUtils } from './properties.utils';
import { DynamicElementModule } from 'app/ng2/components/dynamic-element/dynamic-element.module';
import { DynamicPropertyComponent } from './../../components/properties-table/dynamic-property/dynamic-property.component';
-import {ConfirmationDeleteInputComponent} from "app/ng2/components/inputs-table/confirmation-delete-input/confirmation-delete-input.component"
-import { PopoverModule } from "../../components/popover/popover.module"
+import { PopoverModule } from "../../components/popover/popover.module";
+import { ModalModule } from "../../components/modal/modal.module";
import { FilterPropertiesAssignmentComponent } from "./../../components/filter-properties-assignment/filter-properties-assignment.component";
import { GroupByPipe } from 'app/ng2/pipes/groupBy.pipe';
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 { ModalComponent } from "app/ng2/components/modal/modal.component"
import {LoaderComponent} from "app/ng2/components/loader/loader.component"
import {HttpInterceptor} from "../../services/http.interceptor.service";
@@ -63,8 +62,6 @@ import {HttpInterceptor} from "../../services/http.interceptor.service";
// PopoverContentComponent,
// PopoverComponent,
FilterPropertiesAssignmentComponent,
- ModalComponent,
- ConfirmationDeleteInputComponent,
LoaderComponent
],
imports: [
@@ -75,7 +72,8 @@ import {HttpInterceptor} from "../../services/http.interceptor.service";
CheckboxModule,
DynamicElementModule,
PopoverModule,
- TooltipModule
+ TooltipModule,
+ ModalModule
],
entryComponents: [PropertiesAssignmentComponent],
exports: [
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 ab059b1240..8151d001e8 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
@@ -27,7 +27,6 @@
.left-column {
flex: 1 0 500px;
position: relative;
- margin: 0 0 1em 0;
/deep/ .tabs {
width:33%;
@@ -119,7 +118,7 @@
display:flex;
flex:0 0 350px;
flex-direction:column;
- margin: 45px 0 1em 1em;
+ margin: 45px 0 0 1em;
overflow-x:auto;
/deep/ .tabs {
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 30ba6c0755..6782b72fa2 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
@@ -170,6 +170,10 @@ export class PropertiesAssignmentComponent {
});
}
+ if(resourceInstance.componentName === "vnfConfiguration") {
+ this.isReadonly = true;
+ }
+
if( this.searchPropertyName ){
this.clearSearch();
}
@@ -298,7 +302,7 @@ export class PropertiesAssignmentComponent {
angular.forEach(instancesIds, (instanceId: string): void => {
let selectedInstanceData: ResourceInstance = this.instances.find(instance => instance.uniqueId == instanceId);
- let originType: string = (selectedInstanceData) ? selectedInstanceData.originType : this.selectedInstanceType;
+ let originType: string = (selectedInstanceData) ? selectedInstanceData.originType : this.selectedInstanceType;
if (!this.isInput(originType)) {
selectedProperties[instanceId] = this.propertiesService.getCheckedProperties(this.instanceFePropertiesMap[instanceId]);
} else {
@@ -408,7 +412,7 @@ export class PropertiesAssignmentComponent {
};
private isInput = (instanceType:string):boolean =>{
- return instanceType === ResourceType.VF || instanceType === ResourceType.PNF;
+ return instanceType === ResourceType.VF || instanceType === ResourceType.PNF || instanceType === ResourceType.CVFC;
}
}
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 f876af7f8a..a04d23a16a 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
@@ -139,8 +139,11 @@ export class PropertiesUtils {
let propNameInObj = prop.propertiesName.substring(prop.propertiesName.indexOf(parentName) + parentName.length + 1).split('#').join('.'); //extract everything after parent name
prop.valueObj = _.get(parentValueJSON, propNameInObj, prop.value || prop.defaultValue); //assign value -first value of parent if exists. If not, prop.value if not, prop.defaultvalue
- if ((prop.derivedDataType == DerivedPropertyType.SIMPLE || prop.isDeclared) && typeof prop.valueObj == 'object') { //Stringify objects that should be strings
+ if ( prop.isDeclared && typeof prop.valueObj == 'object') { //Stringify objects of items that are declared
prop.valueObj = JSON.stringify(prop.valueObj);
+ } else if(typeof prop.valueObj == PROPERTY_TYPES.STRING
+ && (prop.type == PROPERTY_TYPES.INTEGER || prop.type == PROPERTY_TYPES.FLOAT || prop.type == PROPERTY_TYPES.BOOLEAN)){ //parse ints and non-string simple types
+ prop.valueObj = JSON.parse(prop.valueObj);
} else { //parse strings that should be objects
if (prop.derivedDataType == DerivedPropertyType.COMPLEX && typeof prop.valueObj != 'object') {
prop.valueObj = JSON.parse(prop.valueObj || '{}');
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 c6865fde9d..cd593d5e3e 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
@@ -59,8 +59,6 @@ export class ComponentServiceNg2 {
private getServerTypeUrl = (componentType:string):string => {
switch (componentType) {
- case ComponentType.PRODUCT:
- return ServerTypeUrl.PRODUCTS;
case ComponentType.SERVICE:
return ServerTypeUrl.SERVICES;
default:
diff --git a/catalog-ui/src/app/ng2/services/http.interceptor.service.ts b/catalog-ui/src/app/ng2/services/http.interceptor.service.ts
index e1653cf0bc..c90bfd2848 100644
--- a/catalog-ui/src/app/ng2/services/http.interceptor.service.ts
+++ b/catalog-ui/src/app/ng2/services/http.interceptor.service.ts
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,8 +21,8 @@
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 {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";
@@ -31,23 +31,23 @@ 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 cookieService:Cookie2Service;
private sharingService:SharingService;
+
constructor() {
- let injector = ReflectiveInjector.resolveAndCreate([Cookie2Service,SharingService]);
+ let injector = ReflectiveInjector.resolveAndCreate([Cookie2Service, SharingService]);
this.cookieService = injector.get(Cookie2Service);
this.sharingService = injector.get(SharingService);
}
- public interceptBefore(request: InterceptedRequest): InterceptedRequest {
-
+ 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);
@@ -56,7 +56,6 @@ export class HttpInterceptor implements Interceptor {
}
request.options.headers.set('X-ECOMP-RequestID', UUID.UUID());
return request;
-
}
public interceptAfter(response:InterceptedResponse):InterceptedResponse {
@@ -66,10 +65,9 @@ export class HttpInterceptor implements Interceptor {
//console.log("Error from BE:",response);
}
return response;
-
}
- private getUuidValue = (url: string) :string => {
+ 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) => {
@@ -158,9 +156,7 @@ export class HttpInterceptor implements Interceptor {
severity: SEVERITY.ERROR
};
}
- // let modalsHandler = this.$injector.get('ModalsHandler');
- // this.modalsHandler.openServerMessageModal(data);
console.error('ERROR data',data);
}
}
diff --git a/catalog-ui/src/app/ng2/services/modal.service.ts b/catalog-ui/src/app/ng2/services/modal.service.ts
new file mode 100644
index 0000000000..32192f40c2
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/modal.service.ts
@@ -0,0 +1,73 @@
+import { Injectable, Type, ViewContainerRef, ApplicationRef, ComponentFactory, ComponentFactoryResolver, ComponentRef } from '@angular/core';
+import { ModalModel, ButtonModel } from 'app/models';
+import { ModalComponent } from 'app/ng2/components/modal/modal.component';
+
+
+@Injectable()
+export class ModalService {
+ currentModal: ComponentRef<any>;
+
+
+ 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. */
+ 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]);
+ this.createCustomModal(modalModel).instance.open();
+ }
+
+
+ /**
+ * 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
+ * @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) => {
+ 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();
+ }
+
+
+ /* 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> => {
+ let customModal: ComponentRef<ModalComponent> = this.createDynamicComponent(ModalComponent);
+ customModal.instance.input = customModalData;
+ this.currentModal = customModal;
+
+ return customModal;
+ }
+
+
+ public closeCurrentModal = () => {
+ if (!this.currentModal) return;
+ this.currentModal.instance.close();
+ this.currentModal.destroy();
+ }
+
+
+ //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> {
+
+ viewContainerRef = viewContainerRef || this.getRootViewContainerRef();
+ viewContainerRef.clear();
+
+ let factory: ComponentFactory<any> = this.componentFactoryResolver.resolveComponentFactory(componentType); //Ref: https://angular.io/guide/dynamic-component-loader
+ let componentRef = viewContainerRef.createComponent(factory);
+
+ return componentRef;
+ }
+
+
+ private getRootViewContainerRef(): ViewContainerRef {
+ return this.applicationRef.components[0].instance.viewContainerRef;
+ }
+} \ No newline at end of file
diff --git a/catalog-ui/src/app/services.ts b/catalog-ui/src/app/services.ts
index ce4a8e32d3..5dd08c2d20 100644
--- a/catalog-ui/src/app/services.ts
+++ b/catalog-ui/src/app/services.ts
@@ -27,7 +27,6 @@ export * from './services/cache-service';
export * from './services/configuration-ui-service';
export * from './services/category-resource-service';
export * from './services/components/component-service';
-export * from './services/components/product-service';
export * from './services/components/resource-service';
export * from './services/components/service-service';
export * from './services/components/resource-service';
diff --git a/catalog-ui/src/app/services/available-icons-service.ts b/catalog-ui/src/app/services/available-icons-service.ts
index ebb6c5ff77..13b6caea2a 100644
--- a/catalog-ui/src/app/services/available-icons-service.ts
+++ b/catalog-ui/src/app/services/available-icons-service.ts
@@ -81,23 +81,6 @@ export class AvailableIconsService implements IAvailableIconsService {
'firewall'
];
break;
-
- case ComponentType.PRODUCT:
- icons = [
- 'vfw',
- 'network',
- 'security',
- 'cloud',
- 'setting',
- 'orphan',
- 'wanx',
- 'vrouter',
- 'ucpe',
- 'mobility'
-
- ];
- break;
-
}
return icons;
}
diff --git a/catalog-ui/src/app/services/components/product-service.ts b/catalog-ui/src/app/services/components/product-service.ts
deleted file mode 100644
index 09199ea172..0000000000
--- a/catalog-ui/src/app/services/components/product-service.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-/**
- * Created by obarda on 2/8/2016.
- */
-'use strict';
-import {IComponentService, ComponentService} from "./component-service";
-import {SharingService} from "../sharing-service";
-import {Product, Component, IAppConfigurtaion} from "../../models";
-
-export interface IProductService extends IComponentService {
-
-}
-
-export class ProductService extends ComponentService implements IProductService {
-
- static '$inject' = [
- 'Restangular',
- 'sdcConfig',
- 'Sdc.Services.SharingService',
- '$q',
- '$base64'
- ];
-
- constructor(protected restangular:restangular.IElement,
- protected sdcConfig:IAppConfigurtaion,
- protected sharingService:SharingService,
- protected $q:ng.IQService,
- protected $base64:any) {
- super(restangular, sdcConfig, sharingService, $q, $base64);
- this.restangular = restangular.one("products");
- }
-
- createComponentObject = (component:Component):Component => {
- return new Product(this, this.$q, <Product>component);
- };
-}
diff --git a/catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts b/catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts
index 52cb78f6d5..a1fa65159f 100644
--- a/catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts
+++ b/catalog-ui/src/app/services/components/utils/composition-left-palette-service.ts
@@ -28,6 +28,7 @@ import {ComponentFactory} from "../../../utils/component-factory";
import {IAppConfigurtaion} from "../../../models/app-config";
import {ResourceType, ComponentType, EVENTS} from "../../../utils/constants";
import {ComponentMetadata} from "../../../models/component-metadata";
+import {Resource} from "app/models/components/resource";
export class LeftPaletteDataObject {
displayLeftPanelComponents:Array<LeftPaletteComponent>;
@@ -58,24 +59,27 @@ export class LeftPaletteLoaderService {
protected EventListenerService:EventListenerService) {
this.restangular.setBaseUrl(sdcConfig.api.root + sdcConfig.api.component_api_root);
-
+
}
private serviceLeftPaletteData:LeftPaletteDataObject;
private resourceLeftPaletteData:LeftPaletteDataObject;
- private productLeftPaletteData:LeftPaletteDataObject;
+ private resourcePNFLeftPaletteData:LeftPaletteDataObject;
private vlData:LeftPaletteDataObject;
- public loadLeftPanel = (componentType: string):void => {
+ public loadLeftPanel = (component:Component):void => {
this.serviceLeftPaletteData = new LeftPaletteDataObject(EVENTS.SERVICE_LEFT_PALETTE_UPDATE_EVENT);
this.resourceLeftPaletteData = new LeftPaletteDataObject(EVENTS.RESOURCE_LEFT_PALETTE_UPDATE_EVENT);
- this.updateComponentLeftPalette(componentType);
+ this.resourcePNFLeftPaletteData = new LeftPaletteDataObject(EVENTS.RESOURCE_PNF_LEFT_PALETTE_UPDATE_EVENT);
+ this.updateComponentLeftPalette(component);
}
-
- private getTypeUrl = (componentType:string):string => {
- return ComponentType.PRODUCT === componentType ? "services" : "resources";
- };
+ private getResourceLeftPaletteDataByResourceType = (resourceType:string):LeftPaletteDataObject => {
+ if(resourceType == ResourceType.PNF) {
+ return this.resourcePNFLeftPaletteData;
+ }
+ return this.resourceLeftPaletteData;
+ }
private onFinishLoading = (componentType:string, leftPaletteData:LeftPaletteDataObject):void => {
this.EventListenerService.notifyObservers(leftPaletteData.onFinishLoadingEvent);
@@ -83,7 +87,7 @@ export class LeftPaletteLoaderService {
private updateLeftPalette = (componentType, componentInternalType:string, leftPaletteData:LeftPaletteDataObject):void => {
- this.restangular.one(this.getTypeUrl(componentType)).one('/latestversion/notabstract/metadata').get({'internalComponentType': componentInternalType}).then((leftPaletteComponentMetadata:Array<ComponentMetadata>) => {
+ this.restangular.one("resources").one('/latestversion/notabstract/metadata').get({'internalComponentType': componentInternalType}).then((leftPaletteComponentMetadata:Array<ComponentMetadata>) => {
_.forEach(leftPaletteComponentMetadata, (componentMetadata:ComponentMetadata) => {
leftPaletteData.displayLeftPanelComponents.push(new LeftPaletteComponent(componentMetadata));
});
@@ -91,30 +95,25 @@ export class LeftPaletteLoaderService {
});
};
- public getLeftPanelComponentsForDisplay = (componentType:string):Array<LeftPaletteComponent> => {
- switch (componentType) {
+ public getLeftPanelComponentsForDisplay = (component:Component):Array<LeftPaletteComponent> => {
+ switch (component.componentType) {
case ComponentType.SERVICE:
return this.serviceLeftPaletteData.displayLeftPanelComponents;
- case ComponentType.PRODUCT:
- return this.productLeftPaletteData.displayLeftPanelComponents;
- default:
- return this.resourceLeftPaletteData.displayLeftPanelComponents;
+ default://resource
+ return this.getResourceLeftPaletteDataByResourceType((<Resource>component).resourceType).displayLeftPanelComponents;
}
};
- public updateComponentLeftPalette = (componentType):void => {
- switch (componentType) {
- case ResourceType.VL:
- this.updateLeftPalette(ComponentType.RESOURCE, ResourceType.VL, this.vlData);
- break;
+ public updateComponentLeftPalette = (component:Component):void => {
+ switch (component.componentType) {
case ComponentType.SERVICE:
this.updateLeftPalette(ComponentType.SERVICE, ComponentType.SERVICE, this.serviceLeftPaletteData);
break;
- case ComponentType.PRODUCT:
- this.updateLeftPalette(ComponentType.PRODUCT, ComponentType.SERVICE, this.productLeftPaletteData);
+ case ComponentType.RESOURCE:
+ this.updateLeftPalette(ComponentType.RESOURCE, (<Resource>component).resourceType, this.getResourceLeftPaletteDataByResourceType((<Resource>component).resourceType));
break;
default:
- this.updateLeftPalette(ComponentType.RESOURCE, ResourceType.VF, this.resourceLeftPaletteData);
+ console.log('ERROR: Component type '+ component.componentType + ' is not exists');
}
};
}
diff --git a/catalog-ui/src/app/services/data-types-service.ts b/catalog-ui/src/app/services/data-types-service.ts
index a6dbf7f12d..84fe42e9f3 100644
--- a/catalog-ui/src/app/services/data-types-service.ts
+++ b/catalog-ui/src/app/services/data-types-service.ts
@@ -132,7 +132,8 @@ export class DataTypesService implements IDataTypesService {
public isDataTypeForDataTypePropertyType = (property:DataTypePropertyModel):boolean=> {
property.simpleType = "";
- if (property.type && PROPERTY_DATA.TYPES.indexOf(property.type) > -1) {
+ let isScalarForNFoD:boolean = property.type === 'scalar-unit.size';
+ if (property.type && PROPERTY_DATA.TYPES.indexOf(property.type) > -1 || isScalarForNFoD) {
return false;
}
let simpleType = this.getTypeForDataTypeDerivedFromSimple(property.type);
diff --git a/catalog-ui/src/app/services/entity-service.ts b/catalog-ui/src/app/services/entity-service.ts
index a255dcff34..75ea036b3e 100644
--- a/catalog-ui/src/app/services/entity-service.ts
+++ b/catalog-ui/src/app/services/entity-service.ts
@@ -19,7 +19,7 @@
*/
'use strict';
-import {Product, Service, IApi, IAppConfigurtaion, Resource, Component} from "../models";
+import { Service, IApi, IAppConfigurtaion, Resource, Component} from "../models";
import {SharingService} from "./sharing-service";
import {ComponentFactory} from "../utils/component-factory";
import {CacheService} from "./cache-service";
@@ -31,7 +31,6 @@ interface IEntityService {
interface IComponentsArray {
services:Array<Service>;
resources:Array<Resource>;
- products:Array<Product>;
}
export class EntityService implements IEntityService {
@@ -66,13 +65,6 @@ export class EntityService implements IEntityService {
this.sharingService.addUuidValue(component.uniqueId, component.uuid);
});
- followedResponse.products.forEach((productResponse:Product) => {
-
- let component:Product = this.ComponentFactory.createProduct(productResponse);
- componentsList.push(component);
- this.sharingService.addUuidValue(component.uniqueId, component.uuid);
- });
-
this.cacheService.set('breadcrumbsComponents', componentsList);
defer.resolve(componentsList);
},(responce) => {
@@ -99,12 +91,7 @@ export class EntityService implements IEntityService {
componentsList.push(component);
this.sharingService.addUuidValue(component.uniqueId, component.uuid);
});
-
- componentResponse.products && componentResponse.products.forEach((productsResponse:Product) => {
- let component:Product = this.ComponentFactory.createProduct(productsResponse);
- componentsList.push(component);
- this.sharingService.addUuidValue(component.uniqueId, component.uuid);
- });
+
this.cacheService.set('breadcrumbsComponents', componentsList);
defer.resolve(componentsList);
});
diff --git a/catalog-ui/src/app/utils/component-factory.ts b/catalog-ui/src/app/utils/component-factory.ts
index c202a1c8f5..b35918c0f6 100644
--- a/catalog-ui/src/app/utils/component-factory.ts
+++ b/catalog-ui/src/app/utils/component-factory.ts
@@ -20,8 +20,8 @@
'use strict';
import {DEFAULT_ICON, ResourceType, ComponentType} from "./constants";
-import {ServiceService, CacheService, ResourceService, ProductService} from "app/services";
-import {IMainCategory, ISubCategory, ICsarComponent, Component, Resource, Service, Product} from "app/models";
+import {ServiceService, CacheService, ResourceService} from "app/services";
+import {IMainCategory, ISubCategory, ICsarComponent, Component, Resource, Service} from "app/models";
import {ComponentMetadata} from "../models/component-metadata";
import {ComponentServiceNg2} from "../ng2/services/component-services/component.service";
import {ComponentGenericResponse} from "../ng2/services/responses/component-generic-response";
@@ -32,7 +32,6 @@ export class ComponentFactory {
static '$inject' = [
'Sdc.Services.Components.ResourceService',
'Sdc.Services.Components.ServiceService',
- 'Sdc.Services.Components.ProductService',
'Sdc.Services.CacheService',
'$q',
'ComponentServiceNg2'
@@ -40,7 +39,6 @@ export class ComponentFactory {
constructor(private ResourceService:ResourceService,
private ServiceService:ServiceService,
- private ProductService:ProductService,
private cacheService:CacheService,
private $q:ng.IQService,
private ComponentServiceNg2: ComponentServiceNg2) {
@@ -58,18 +56,10 @@ export class ComponentFactory {
newComponent = new Resource(this.ResourceService, this.$q, <Resource> component);
break;
- case 'PRODUCT':
- newComponent = new Product(this.ProductService, this.$q, <Product> component);
- break;
}
return newComponent;
};
- public createProduct = (product:Product):Product => {
- let newProduct:Product = new Product(this.ProductService, this.$q, <Product> product);
- return newProduct;
- };
-
public createService = (service:Service):Service => {
let newService:Service = new Service(this.ServiceService, this.$q, <Service> service);
return newService;
@@ -144,12 +134,10 @@ export class ComponentFactory {
case ResourceType.VL:
case ResourceType.VFC:
case ResourceType.CP:
+ case ResourceType.PNF:
+ case ResourceType.CVFC:
newComponent = new Resource(this.ResourceService, this.$q);
break;
-
- case ComponentType.PRODUCT:
- newComponent = new Product(this.ProductService, this.$q);
- break;
}
newComponent.componentType = componentType;
newComponent.tags = [];
diff --git a/catalog-ui/src/app/utils/component-instance-factory.ts b/catalog-ui/src/app/utils/component-instance-factory.ts
index c020c53705..9e25e6b02f 100644
--- a/catalog-ui/src/app/utils/component-instance-factory.ts
+++ b/catalog-ui/src/app/utils/component-instance-factory.ts
@@ -21,7 +21,7 @@
* Created by obarda on 3/7/2016.
*/
'use strict';
-import {ComponentInstance, ServiceInstance, ProductInstance, ResourceInstance, Component} from "../models";
+import {ComponentInstance, ServiceInstance, ResourceInstance, Component} from "../models";
import {LeftPaletteComponent} from "../models/components/displayComponent";
export class ComponentInstanceFactory {
@@ -33,10 +33,6 @@ export class ComponentInstanceFactory {
newComponentInstance = new ServiceInstance(componentInstance);
break;
- case 'PRODUCT':
- newComponentInstance = new ProductInstance(componentInstance);
- break;
-
default :
newComponentInstance = new ResourceInstance(componentInstance);
break;
@@ -51,10 +47,6 @@ export class ComponentInstanceFactory {
newComponentInstance = new ServiceInstance();
break;
- case 'PRODUCT':
- newComponentInstance = new ProductInstance();
- break;
-
default :
newComponentInstance = new ResourceInstance();
break;
diff --git a/catalog-ui/src/app/utils/constants.ts b/catalog-ui/src/app/utils/constants.ts
index 636c0c4fbf..d239019455 100644
--- a/catalog-ui/src/app/utils/constants.ts
+++ b/catalog-ui/src/app/utils/constants.ts
@@ -29,13 +29,11 @@ export let CHANGE_COMPONENT_CSAR_VERSION_FLAG = 'changeComponentCsarVersion';
export class ComponentType {
static SERVICE = 'SERVICE';
static RESOURCE = 'RESOURCE';
- static PRODUCT = 'PRODUCT';
}
export class ServerTypeUrl {
static RESOURCES = 'resources/';
static SERVICES = 'services/';
- static PRODUCTS = 'product/';
}
export class ResourceType {
@@ -45,6 +43,7 @@ export class ResourceType {
static VFC = 'VFC';
static VFCMT = 'VFCMT';
static PNF = 'PNF';
+ static CVFC = 'CVFC';
}
export class ComponentState {
@@ -129,8 +128,6 @@ export class PROPERTY_VALUE_CONSTRAINTS {
export class Role {
public static ADMIN = 'ADMIN';
public static DESIGNER = 'DESIGNER';
- public static PRODUCT_STRATEGIST = 'PRODUCT_STRATEGIST';
- public static PRODUCT_MANAGER = 'PRODUCT_MANAGER';
public static TESTER = 'TESTER';
public static OPS = 'OPS';
public static GOVERNOR = 'GOVERNOR';
@@ -213,14 +210,12 @@ export class GraphUIObjects {
export class States {
public static WORKSPACE_GENERAL = 'workspace.general';
- public static WORKSPACE_ICONS = 'workspace.icons';
public static WORKSPACE_ACTIVITY_LOG = 'workspace.activity_log';
public static WORKSPACE_DEPLOYMENT_ARTIFACTS = 'workspace.deployment_artifacts';
public static WORKSPACE_PROPERTIES = 'workspace.properties';
public static WORKSPACE_SERVICE_INPUTS = 'workspace.service_inputs';
public static WORKSPACE_RESOURCE_INPUTS = 'workspace.resource_inputs';
public static WORKSPACE_ATTRIBUTES = 'workspace.attributes';
- public static WORKSPACE_HIERARCHY = 'workspace.hierarchy';
public static WORKSPACE_INFORMATION_ARTIFACTS = 'workspace.information_artifacts';
public static WORKSPACE_TOSCA_ARTIFACTS = 'workspace.tosca_artifacts';
public static WORKSPACE_COMPOSITION = 'workspace.composition';
@@ -237,7 +232,6 @@ export class EVENTS {
static RESOURCE_LEFT_PALETTE_UPDATE_EVENT = "resourceLeftPanelUpdateEvent";
static RESOURCE_PNF_LEFT_PALETTE_UPDATE_EVENT = "resourcePNFLeftPanelUpdateEvent";
static SERVICE_LEFT_PALETTE_UPDATE_EVENT = "serviceLeftPanelUpdateEvent";
- static PRODUCT_LEFT_PALETTE_UPDATE_EVENT = "productLeftPanelUdateEvent";
static VL_LEFT_PALETTE_UPDATE_EVENT = "vlLeftPanelUdateEvent";
static ON_CSAR_LOADING = "onCsarLoading";
static DOWNLOAD_ARTIFACT_FINISH_EVENT = "downloadArtifactFinishEvent";
diff --git a/catalog-ui/src/app/utils/modals-handler.ts b/catalog-ui/src/app/utils/modals-handler.ts
index ae91b2acb7..0d17683116 100644
--- a/catalog-ui/src/app/utils/modals-handler.ts
+++ b/catalog-ui/src/app/utils/modals-handler.ts
@@ -187,6 +187,24 @@ export class ModalsHandler implements IModalsHandler {
return deferred.promise;
};
+ openUpdateIconModal = (component: Component):ng.IPromise<any> => {
+ let deferred = this.$q.defer();
+ let modalOptions:ng.ui.bootstrap.IModalSettings = {
+ templateUrl: '../view-models/modals/icons-modal/icons-modal-view.html',
+ controller: 'Sdc.ViewModels.IconsModalViewModel',
+ size: 'sdc-auto',
+ backdrop: 'static',
+ resolve: {
+ component: ():Component => {
+ return component;
+ }
+ }
+ };
+ let modalInstance:ng.ui.bootstrap.IModalServiceInstance = this.$uibModal.open(modalOptions);
+ deferred.resolve(modalInstance.result);
+ return deferred.promise;
+ };
+
openEditEnvParametersModal = (artifactResource:ArtifactModel, component?:Component):ng.IPromise<any> => {
let deferred = this.$q.defer();
let modalOptions:ng.ui.bootstrap.IModalSettings = {
diff --git a/catalog-ui/src/app/view-models/catalog/catalog-view-model.ts b/catalog-ui/src/app/view-models/catalog/catalog-view-model.ts
index 8925be0fff..ec9e888eed 100644
--- a/catalog-ui/src/app/view-models/catalog/catalog-view-model.ts
+++ b/catalog-ui/src/app/view-models/catalog/catalog-view-model.ts
@@ -117,7 +117,7 @@ export class CatalogViewModel {
let onSuccess = (followedResponse:Array<Component>):void => {
this.$scope.catalogFilterdItems = followedResponse;
this.$scope.isAllItemDisplay = this.$scope.numberOfItemToDisplay >= this.$scope.catalogFilterdItems.length;
- this.$scope.categories = this.cacheService.get('serviceCategories').concat(this.cacheService.get('resourceCategories')).concat(this.cacheService.get('productCategories'));
+ this.$scope.categories = this.cacheService.get('serviceCategories').concat(this.cacheService.get('resourceCategories'));
this.$scope.gui.isLoading = false;
};
@@ -137,7 +137,7 @@ export class CatalogViewModel {
//this.$scope.categories = this.cacheService.get('categoriesMap');
this.$scope.sdcMenu = this.sdcMenu;
this.$scope.confStatus = this.sdcMenu.statuses;
- this.$scope.expandedSection = ["type", "category", "product-category", "status"];
+ this.$scope.expandedSection = ["type", "category", "status"];
this.$scope.user = this.userResourceService.getLoggedinUser();
this.$scope.catalogMenuItem = this.sdcMenu.catalogMenuItem;
this.$scope.version = this.cacheService.get('version');
@@ -147,8 +147,8 @@ export class CatalogViewModel {
// Checklist init
this.$scope.checkboxes = <Checkboxes>{};
- this.$scope.checkboxes.componentTypes = ['Resource', 'Service', 'Product'];
- this.$scope.checkboxes.resourceSubTypes = ['VF', 'VFC', 'CP', 'VL'];
+ this.$scope.checkboxes.componentTypes = ['Resource', 'Service'];
+ this.$scope.checkboxes.resourceSubTypes = ['VF', 'VFC', 'PNF', 'CP', 'VL'];
// Checkboxes filter init
this.$scope.checkboxesFilter = <CheckboxesFilter>{};
diff --git a/catalog-ui/src/app/view-models/catalog/catalog.less b/catalog-ui/src/app/view-models/catalog/catalog.less
index ff50202243..1f473c9638 100644
--- a/catalog-ui/src/app/view-models/catalog/catalog.less
+++ b/catalog-ui/src/app/view-models/catalog/catalog.less
@@ -67,28 +67,6 @@
//text-indent: -10px;
}
- /*Added by - Ikram */
- .i-sdc-product-input,
- .i-sdc-product-select {
- border: 1px solid @border_color_f;
- min-height: 30px;
- padding: 0;
- width: 100%;
- margin: 1px 0;
- background-color: #F2F2F2;
- outline: none;
-
- &:disabled {
- .disabled;
- }
- optgroup{
- color: @color_u;
- option{
- color: @color_b;
- }
- }
- }
-
.i-sdc-categories-list-item-icon {
display: inline-block;
float: right;
diff --git a/catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts b/catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts
index b9e51f098a..5480e4f6cf 100644
--- a/catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts
+++ b/catalog-ui/src/app/view-models/dashboard/dashboard-view-model.ts
@@ -310,6 +310,13 @@ export class DashboardViewModel {
};
+ this.$scope.createPNF = ():void => {
+ this.$state.go('workspace.general', {
+ type: ComponentType.RESOURCE.toLowerCase(),
+ resourceType: ResourceType.PNF
+ });
+ };
+
this.$scope.entitiesCount = (folderItem:FoldersItemsMenu):any => {
let self = this;
let total:number = 0;
diff --git a/catalog-ui/src/app/view-models/dashboard/dashboard-view.html b/catalog-ui/src/app/view-models/dashboard/dashboard-view.html
index 806bb8138d..baf4aa6e51 100644
--- a/catalog-ui/src/app/view-models/dashboard/dashboard-view.html
+++ b/catalog-ui/src/app/view-models/dashboard/dashboard-view.html
@@ -13,15 +13,15 @@
<div class='w-sdc-row-flex-items'>
<!-- ADD Component -->
- <div ng-if="user.role === 'DESIGNER' || user.role === 'PRODUCT_MANAGER'" class="w-sdc-dashboard-card-new"
+ <div ng-if="user.role === 'DESIGNER'" class="w-sdc-dashboard-card-new"
data-ng-mouseleave="displayActions = false"
data-ng-mouseover="displayActions = true"
data-ng-init="displayActions = false">
<div class="w-sdc-dashboard-card-new-content" data-tests-id="AddButtonsArea">
<div class="w-sdc-dashboard-card-new-content-plus" data-ng-show="!displayActions"></div>
<div class="sdc-dashboard-create-element-container" data-ng-show="displayActions">
- <button data-ng-if="roles[user.role].dashboard.showCreateNewProduct" data-tests-id="createProductButton" class="tlv-btn outline blue" data-ng-click="openCreateModal('PRODUCT')">Create Product</button>
<button data-ng-if="roles[user.role].dashboard.showCreateNew" data-tests-id="createResourceButton" class="tlv-btn outline blue" data-ng-click="openCreateModal('RESOURCE')">Add VF</button>
+ <button data-ng-if="roles[user.role].dashboard.showCreateNew" data-tests-id="createPNFButton" class="tlv-btn outline blue" data-ng-click="createPNF()">Add PNF</button>
<button data-ng-if="roles[user.role].dashboard.showCreateNew" data-tests-id="createServiceButton" class="tlv-btn outline blue" data-ng-click="openCreateModal('SERVICE')">Add Service</button>
</div>
</div>
@@ -44,8 +44,8 @@
</div>
</div>
</div>
- </div>
-
+ </div>
+
<!-- Tile new -->
<div class="sdc-tile-catalog sdc-tile-fix-width" data-ng-repeat="component in components | filter:{resourceType:('!'+vfcmtType)} | entityFilter:checkboxesFilter | filter:search">
@@ -62,7 +62,7 @@
data-tests-id="{{component.name}}"></div>
</div>
<div class='sdc-tile-content-info'>
- <div class="sdc-tile-content-info-item-name" data-tests-id="{{component.name | resourceName}}" sdc-smart-tooltip>{{component.name | resourceName}}</div>
+ <div class="sdc-tile-content-info-item-name" data-tests-id="{{component.name | resourceName}}" sdc-smart-tooltip>{{component.name | resourceName}}</div>
<div class="sdc-tile-content-info-version-info">
<div class="sdc-tile-content-info-version-info-text" data-tests-id="{{component.name}}Version">V {{component.version}}</div>
</div>
@@ -70,11 +70,11 @@
</div>
<div class='sdc-tile-footer'>
<div class='sdc-tile-footer-text'>{{component.getStatus(sdcMenu)}}</div>
- </div>
+ </div>
</div>
<!-- Tile new -->
-
+
</div>
</perfect-scrollbar>
diff --git a/catalog-ui/src/app/view-models/dashboard/dashboard.less b/catalog-ui/src/app/view-models/dashboard/dashboard.less
index 7993390769..02280cdb42 100644
--- a/catalog-ui/src/app/view-models/dashboard/dashboard.less
+++ b/catalog-ui/src/app/view-models/dashboard/dashboard.less
@@ -244,13 +244,6 @@
}
}
- &.PRODUCT {
- .b_14_m;
- &::before {
- content: 'P';
- }
- }
-
&.green {
.d_12;
&::before {
diff --git a/catalog-ui/src/app/view-models/dcae-app/dcae-app.less b/catalog-ui/src/app/view-models/dcae-app/dcae-app.less
index bc1404d7c4..71a3101412 100644
--- a/catalog-ui/src/app/view-models/dcae-app/dcae-app.less
+++ b/catalog-ui/src/app/view-models/dcae-app/dcae-app.less
@@ -48,28 +48,6 @@
//text-indent: -10px;
}
- /*Added by - Ikram */
- .i-sdc-product-input,
- .i-sdc-product-select {
- border: 1px solid @border_color_f;
- min-height: 30px;
- padding: 0;
- width: 100%;
- margin: 1px 0;
- background-color: #F2F2F2;
- outline: none;
-
- &:disabled {
- .disabled;
- }
- optgroup{
- color: @color_u;
- option{
- color: @color_b;
- }
- }
- }
-
.i-sdc-categories-list-item-icon {
display: inline-block;
float: right;
diff --git a/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts b/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts
index 8b9acbcab7..ee2e94f934 100644
--- a/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts
+++ b/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view-model.ts
@@ -23,6 +23,7 @@ import {
PROPERTY_TYPES, ModalsHandler, ValidationUtils, PROPERTY_VALUE_CONSTRAINTS, FormState, PROPERTY_DATA} from "app/utils";
import {DataTypesService} from "app/services";
import {PropertyModel, DataTypesMap, Component} from "app/models";
+import {ComponentInstance} from "../../../../models/componentsInstances/componentInstance";
export interface IEditPropertyModel {
property:PropertyModel;
@@ -50,6 +51,7 @@ interface IPropertyFormViewModelScope extends ng.IScope {
isTypeDataType:boolean;
maxLength:number;
isPropertyValueOwner:boolean;
+ isVnfConfiguration:boolean;
validateJson(json:string):boolean;
save(doNotCloseModal?:boolean):void;
@@ -192,6 +194,17 @@ export class PropertyFormViewModel {
this.$scope.isPropertyValueOwner = this.isPropertyValueOwner;
this.initEditPropertyModel();
+ //check if property of VnfConfiguration
+ this.$scope.isVnfConfiguration = false;
+ if(angular.isArray(this.component.componentInstances)) {
+ var componentPropertyOwner:ComponentInstance = this.component.componentInstances.find((ci:ComponentInstance) => {
+ return ci.uniqueId === this.property.resourceInstanceUniqueId;
+ });
+ if (componentPropertyOwner.componentName === 'vnfConfiguration') {
+ this.$scope.isVnfConfiguration = true;
+ }
+ }
+
this.$scope.nonPrimitiveTypes = _.filter(Object.keys(this.$scope.dataTypes), (type:string)=> {
return this.$scope.editPropertyModel.types.indexOf(type) == -1;
});
diff --git a/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view.html b/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view.html
index f92d9a5ddc..743de298cd 100644
--- a/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view.html
+++ b/catalog-ui/src/app/view-models/forms/property-forms/component-property-form/property-form-view.html
@@ -142,7 +142,7 @@
schema-property="editPropertyModel.property.schema.property"
parent-form-obj="forms.editForm"
fields-prefix-name="currentPropertyIndex"
- read-only="editPropertyModel.property.readonly && !isPropertyValueOwner"
+ read-only="(editPropertyModel.property.readonly && !isPropertyValueOwner) || isVnfConfiguration"
default-value="{{getDefaultValue()}}"
max-length="maxLength"></type-map>
</div>
diff --git a/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.html b/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.html
new file mode 100644
index 0000000000..4b89701201
--- /dev/null
+++ b/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.html
@@ -0,0 +1,18 @@
+<sdc-modal modal="modalIcons" type="classic" class="w-sdc-modal-icons" buttons="footerButtons" header="Choose Icon" show-close-button="true">
+
+ <div class="suggested-icons-container">
+ <div class ="suggested-icon-wrapper" data-ng-class="{'selected': selectedIcon == iconSrc}" data-ng-repeat="iconSrc in icons track by $index">
+ <div class="i-sdc-form-item-suggested-icon large hand {{iconSprite}} {{iconSrc}}"
+ data-tests-id="{{iconSrc}} iconBox"
+ data-ng-click="changeIcon(iconSrc)"
+ tooltips tooltip-content='{{iconSrc | translate}}'
+ >
+ </div>
+ </div>
+ </div>
+
+ <div class="w-sdc-modal-footer classic">
+ <button class="tlv-btn blue" data-tests-id="OK" data-ng-click="updateIcon()">OK</button>
+ <button class="tlv-btn grey" data-tests-id="Cancel" data-ng-click="cancel()" >Cancel</button>
+ </div>
+</sdc-modal>
diff --git a/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.less b/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.less
new file mode 100644
index 0000000000..660846c883
--- /dev/null
+++ b/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.less
@@ -0,0 +1,33 @@
+.suggested-icons-container {
+ text-align: left;
+ width: 370px;
+ margin-bottom: 20px;
+ position: relative;
+
+ .suggested-icon-wrapper {
+ padding: 5px;
+ margin: 14px 0 14px 28px;
+ display: inline-block;
+ height: 71px;
+ width: 71px;
+
+ &.selected {
+ border: 2px solid @main_color_a;
+ border-radius: 35px;
+ display: inline-block;
+ line-height: 0px;
+ padding: 3px;
+ }
+
+ }
+ .i-sdc-form-item-suggested-icon {
+ opacity: 0.8;
+ &:hover{
+ opacity: 1;
+ }
+ }
+ .suggested-icon-wrapper:nth-child(4n+1) {
+ margin-left: 0;
+ }
+}
+
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/icons/icons-view-model.ts b/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.ts
index c25bc4a1f1..eeadcd4e83 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/icons/icons-view-model.ts
+++ b/catalog-ui/src/app/view-models/modals/icons-modal/icons-modal-view.ts
@@ -19,53 +19,60 @@
*/
/**
- * Created by obarda on 4/4/2016.
+ * Created by rc2122 on 7/4/2017.
*/
'use strict';
import {ComponentFactory} from "app/utils";
import {AvailableIconsService} from "app/services";
import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
import {IMainCategory, ISubCategory} from "app/models";
-
-export interface IIconsScope extends IWorkspaceViewModelScope {
- icons:Array<string>;
- iconSprite:string;
- setComponentIcon(iconSrc:string):void;
+import {Component} from "app/models";
+import {ResourceType} from "app/utils/constants";
+
+interface IIconsModalViewModelScope {
+ modalIcons:ng.ui.bootstrap.IModalServiceInstance;
+ icons:Array<string>,
+ iconSprite:string,
+ selectedIcon:string,
+ changeIcon(icon:string):void,
+ cancel():void
+ updateIcon():void;
}
-export class IconsViewModel {
-
+export class IconsModalViewModel {
static '$inject' = [
'$scope',
'Sdc.Services.AvailableIconsService',
'ComponentFactory',
- '$state'
+ '$state',
+ '$uibModalInstance',
+ 'component'
];
- constructor(private $scope:IIconsScope,
+ constructor(private $scope:IIconsModalViewModelScope,
private availableIconsService:AvailableIconsService,
private ComponentFactory:ComponentFactory,
- private $state:ng.ui.IStateService) {
-
-
+ private $state:ng.ui.IStateService,
+ private $uibModalInstance:ng.ui.bootstrap.IModalServiceInstance,
+ private component: Component) {
this.initScope();
- this.initIcons();
- this.$scope.updateSelectedMenuItem();
- this.$scope.iconSprite = this.$scope.component.iconSprite;
+ this._initIcons();
+ this.$scope.iconSprite = this.component.iconSprite;
+ this.$scope.selectedIcon = this.component.icon;
- if (this.$scope.component.isResource()) {
+ if (this.component.isResource()) {
this.initVendor();
}
+
}
- private initialIcon:string = this.$scope.component.icon;
- private initIcons = ():void => {
+ private _initIcons = ():void => {
// For subcategories that where created by admin, there is no icons
this.$scope.icons = new Array<string>();
- if (this.$scope.component.categories && this.$scope.component.categories.length > 0) {
+ if (this.component.categories && this.component.categories.length > 0) {
- _.forEach(this.$scope.component.categories, (category:IMainCategory):void => {
+ _.forEach(this.component.categories, (category:IMainCategory):void => {
if (category.icons) {
this.$scope.icons = this.$scope.icons.concat(category.icons);
}
@@ -79,26 +86,26 @@ export class IconsViewModel {
});
}
- if (this.$scope.component.isResource()) {
- let resourceType:string = this.$scope.component.getComponentSubType();
- if (resourceType === 'VL') {
+ if (this.component.isResource()) {
+ let resourceType:string = this.component.getComponentSubType();
+ if (resourceType === ResourceType.VL) {
this.$scope.icons = ['vl'];
}
- if (resourceType === 'CP') {
+ if (resourceType === ResourceType.CP) {
this.$scope.icons = ['cp'];
}
}
if (this.$scope.icons.length === 0) {
- this.$scope.icons = this.availableIconsService.getIcons(this.$scope.component.componentType);
+ this.$scope.icons = this.availableIconsService.getIcons(this.component.componentType);
}
//we always add the defual icon to the list
this.$scope.icons.push('defaulticon');
};
private initVendor = ():void => {
- let vendors:Array<string> = this.availableIconsService.getIcons(this.$scope.component.componentType).slice(5, 19);
- let vendorName = this.$scope.component.vendorName.toLowerCase();
+ let vendors:Array<string> = this.availableIconsService.getIcons(this.component.componentType).slice(5, 19);
+ let vendorName = this.component.vendorName.toLowerCase();
if ('at&t' === vendorName) {
vendorName = 'att';
}
@@ -115,17 +122,22 @@ export class IconsViewModel {
};
private initScope():void {
+ this.$scope.modalIcons = this.$uibModalInstance;
this.$scope.icons = [];
- this.$scope.setValidState(true);
- //if(this.$scope.component.icon === DEFAULT_ICON){
- // //this.$scope.setValidState(false);
- //}
-
- this.$scope.setComponentIcon = (iconSrc:string):void => {
- this.$state.current.data.unsavedChanges = !this.$scope.isViewMode() && (iconSrc != this.initialIcon);
- this.$scope.component.icon = iconSrc;
- // this.$scope.setValidState(true);
+ this.$scope.changeIcon = (icon:string):void => {
+ this.$scope.selectedIcon = icon;
};
-
+ this.$scope.cancel = ():void => {
+ this.$uibModalInstance.dismiss();
+ };
+ this.$scope.updateIcon = ():void => {
+ let isDirty:boolean = this.component.icon != this.$scope.selectedIcon;
+ this.component.icon = this.$scope.selectedIcon;
+ this.$uibModalInstance.close(isDirty);
+ }
}
+
}
+
+
+
diff --git a/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor.less b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor.less
index bc1404d7c4..71a3101412 100644
--- a/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor.less
+++ b/catalog-ui/src/app/view-models/onboard-vendor/onboard-vendor.less
@@ -48,28 +48,6 @@
//text-indent: -10px;
}
- /*Added by - Ikram */
- .i-sdc-product-input,
- .i-sdc-product-select {
- border: 1px solid @border_color_f;
- min-height: 30px;
- padding: 0;
- width: 100%;
- margin: 1px 0;
- background-color: #F2F2F2;
- outline: none;
-
- &:disabled {
- .disabled;
- }
- optgroup{
- color: @color_u;
- option{
- color: @color_b;
- }
- }
- }
-
.i-sdc-categories-list-item-icon {
display: inline-block;
float: right;
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.less b/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.less
index 61bb3e9f01..24f83ec503 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/activity-log/activity-log.less
@@ -1,7 +1,4 @@
.activity-log {
-
- margin-top: 30px;
-
.title-wrapper {
display: flex;
justify-content: flex-end;
@@ -10,7 +7,7 @@
.table-container-flex .table .body .scrollbar-container {
max-height: 448px;
}
-
+
.view-mode {
background-color: @main_color_p;
}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes.less b/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes.less
index ffd28afce4..932daa167d 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/attributes/attributes.less
@@ -13,7 +13,7 @@
}
.table-container-flex {
- margin-top: 27px;
+ margin-top: 0;
.text{
overflow: hidden;
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 894f8aeb2a..fbd32cc967 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
@@ -18,12 +18,14 @@
* ============LICENSE_END=========================================================
*/
'use strict';
-import {Component, Product, ComponentInstance, IAppMenu} from "app/models";
+import {Component, ComponentInstance, IAppMenu} from "app/models";
import {SharingService, CacheService, EventListenerService, LeftPaletteLoaderService} from "app/services";
import {ModalsHandler, GRAPH_EVENTS, ComponentFactory, ChangeLifecycleStateHandler, MenuHandler, EVENTS} from "app/utils";
import {IWorkspaceViewModelScope} from "../../workspace-view-model";
import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service";
import {ComponentGenericResponse} from "app/ng2/services/responses/component-generic-response";
+import {Resource} from "app/models/components/resource";
+import {ResourceType} from "../../../../utils/constants";
export interface ICompositionViewModelScope extends IWorkspaceViewModelScope {
@@ -205,9 +207,6 @@ export class CompositionViewModel {
if (this.$state.current.name === 'workspace.composition.api') {
this.$state.go('workspace.composition.details');
}
- if (this.$state.current.name === 'workspace.composition.relations' && this.$scope.currentComponent.isProduct()) {
- this.$state.go('workspace.composition.details');
- }
};
this.$scope.onBackgroundClick = ():void => {
@@ -238,7 +237,7 @@ export class CompositionViewModel {
this.ModalsHandler.openAlertModal(title, message).then(onOk);
};
- this.$scope.onComponentInstanceVersionChange = (component:Product):void => {
+ this.$scope.onComponentInstanceVersionChange = (component:Component):void => {
this.$scope.currentComponent = component;
this.$scope.setComponent(this.$scope.currentComponent);
this.$scope.updateSelectedComponent();
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html
index 761ae53909..cef942e853 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/composition-view.html
@@ -57,7 +57,8 @@
<button class="i-sdc-designer-sidebar-tab" data-ui-sref-active="active"
data-ui-sref="workspace.composition.deployment"
tooltips tooltip-class="tooltip-custom tab-tooltip" tooltip-content="Deployment Artifacts"
- data-tests-id="deployment-artifact-tab">
+ data-tests-id="deployment-artifact-tab"
+ data-ng-if="!isPNF()">
<div class="i-sdc-designer-sidebar-tab-icon sprite-new deployment-artifacts"></div>
</button>
<button tooltips tooltip-class="tooltip-custom tab-tooltip"
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html
index 01cb9d4ee4..8221c67eca 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/artifacts/artifacts-view.html
@@ -60,7 +60,7 @@
</div>
</div>
- <div class="w-sdc-designer-sidebar-section-footer" data-ng-if="!isViewMode() && artifactType!=='api' && (!isComponentInstanceSelected()||selectedComponent.resourceType=='VF') && !currentComponent.isProduct() && ('deployment' != artifactType || selectedComponent.isComplex())">
+ <div class="w-sdc-designer-sidebar-section-footer" data-ng-if="!isViewMode() && artifactType!=='api' && (!isComponentInstanceSelected()||selectedComponent.resourceType=='VF') && ('deployment' != artifactType || selectedComponent.isComplex())">
<button class="w-sdc-designer-sidebar-section-footer-action tlv-btn blue" data-tests-id="add_Artifact_Button" data-ng-click="addOrUpdate({})" type="button">Add Artifact</button>
</div>
</div>
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts
index 223d6cf964..0d8d17ec73 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view-model.ts
@@ -82,7 +82,7 @@ export class DetailsViewModel {
let highestVersion = _.last(Object.keys(this.$scope.selectedComponent.allVersions));
if (parseFloat(highestVersion) % 1) { //if highest is minor, make sure it is the latest checked in -
- let latestVersionComponent:LeftPaletteComponent = _.maxBy(_.filter(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(this.$scope.currentComponent.componentType), (component:LeftPaletteComponent) => { //latest checked in
+ let latestVersionComponent:LeftPaletteComponent = _.maxBy(_.filter(this.LeftPaletteLoaderService.getLeftPanelComponentsForDisplay(this.$scope.currentComponent), (component:LeftPaletteComponent) => { //latest checked in
return (component.systemName === this.$scope.selectedComponent.systemName
|| component.uuid === this.$scope.selectedComponent.uuid);
}),(component)=>{return component.version});
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view.html b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view.html
index 70dc58075a..8607d65964 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details-view.html
@@ -77,6 +77,27 @@
data-tests-id="rightTab_vendorRelease">
</span>
</div>
+ <div class="i-sdc-designer-sidebar-section-content-item" data-ng-if="selectedComponent.isResource()">
+ <span class="i-sdc-designer-sidebar-section-content-item-label" translate="GENERAL_LABEL_RESOURCE_MODEL_NUMBER"></span>
+ <span class="i-sdc-designer-sidebar-section-content-item-value vendor-model-number" data-ng-bind="selectedComponent.resourceVendorModelNumber"
+ tooltips tooltip-class="tooltip-custom break-word-tooltip" tooltip-content="&#8203;{{selectedComponent.resourceVendorModelNumber}}"
+ data-tests-id="rightTab_resourceVendorModelNumber">
+ </span>
+ </div>
+ <div class="i-sdc-designer-sidebar-section-content-item" data-ng-if="selectedComponent.isService()">
+ <span class="i-sdc-designer-sidebar-section-content-item-label" translate="GENERAL_LABEL_SERVICE_TYPE"></span>
+ <span class="i-sdc-designer-sidebar-section-content-item-value" data-ng-bind="selectedComponent.serviceType"
+ tooltips tooltip-class="tooltip-custom break-word-tooltip" tooltip-content="&#8203;{{selectedComponent.serviceType}}"
+ data-tests-id="rightTab_serviceType">
+ </span>
+ </div>
+ <div class="i-sdc-designer-sidebar-section-content-item" data-ng-if="selectedComponent.isService()">
+ <span class="i-sdc-designer-sidebar-section-content-item-label" translate="GENERAL_LABEL_SERVICE_ROLE"></span>
+ <span class="i-sdc-designer-sidebar-section-content-item-value" data-ng-bind="selectedComponent.serviceRole"
+ tooltips tooltip-class="tooltip-custom break-word-tooltip" tooltip-content="&#8203;{{selectedComponent.serviceRole}}"
+ data-tests-id="rightTab_serviceRole">
+ </span>
+ </div>
<div class="i-sdc-designer-sidebar-section-content-item">
<span class="i-sdc-designer-sidebar-section-content-item-label" translate="GENERAL_LABEL_CONTACT_ID"></span>
<span class="i-sdc-designer-sidebar-section-content-item-value" data-ng-bind="selectedComponent.contactId"
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details.less b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details.less
index 3ebb14c2b8..0ed72e2f00 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/composition/tabs/details/details.less
@@ -37,6 +37,9 @@
max-width: 160px;
vertical-align:bottom;
font-weight: normal;
+ &.vendor-model-number{
+ max-width: 110px;
+ }
&.additional-information{
max-width:160px;
display: inline-block;
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less
index 3596a217b8..f67d088b5a 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/deployment-artifacts/deployment-artifacts.less
@@ -71,7 +71,7 @@
.table-container-flex {
- margin-top: 27px;
+ margin-top: 0;
.text{
overflow: hidden;
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 05b3324bbb..1dc326a7c0 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
@@ -22,14 +22,16 @@
import {ModalsHandler, ValidationUtils, EVENTS, CHANGE_COMPONENT_CSAR_VERSION_FLAG, ComponentType, DEFAULT_ICON,
ResourceType} from "app/utils";
import {CacheService, EventListenerService, ProgressService} from "app/services";
-import {IAppConfigurtaion, Product, IValidate, IMainCategory, Resource, ISubCategory,Service} from "app/models";
+import {IAppConfigurtaion, IValidate, IMainCategory, Resource, ISubCategory,Service} from "app/models";
import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
export class Validation {
componentNameValidationPattern:RegExp;
contactIdValidationPattern:RegExp;
tagValidationPattern:RegExp;
- vendorValidationPattern:RegExp;
+ VendorReleaseValidationPattern:RegExp;
+ VendorNameValidationPattern:RegExp;
+ VendorModelNumberValidationPattern:RegExp;
commentValidationPattern:RegExp;
projectCodeValidationPattern:RegExp;
}
@@ -63,6 +65,8 @@ export interface IGeneralScope extends IWorkspaceViewModelScope {
onEcompGeneratedNamingChange():void;
openOnBoardingModal():void;
initCategoreis():void;
+ updateIcon():void;
+ possibleToUpdateIcon():boolean;
}
export class GeneralViewModel {
@@ -73,7 +77,9 @@ export class GeneralViewModel {
'ComponentNameValidationPattern',
'ContactIdValidationPattern',
'TagValidationPattern',
- 'VendorValidationPattern',
+ 'VendorReleaseValidationPattern',
+ 'VendorNameValidationPattern',
+ 'VendorModelNumberValidationPattern',
'CommentValidationPattern',
'ValidationUtils',
'sdcConfig',
@@ -93,7 +99,9 @@ export class GeneralViewModel {
private ComponentNameValidationPattern:RegExp,
private ContactIdValidationPattern:RegExp,
private TagValidationPattern:RegExp,
- private VendorValidationPattern:RegExp,
+ private VendorReleaseValidationPattern:RegExp,
+ private VendorNameValidationPattern:RegExp,
+ private VendorModelNumberValidationPattern:RegExp,
private CommentValidationPattern:RegExp,
private ValidationUtils:ValidationUtils,
private sdcConfig:IAppConfigurtaion,
@@ -121,7 +129,9 @@ export class GeneralViewModel {
this.$scope.validation.componentNameValidationPattern = this.ComponentNameValidationPattern;
this.$scope.validation.contactIdValidationPattern = this.ContactIdValidationPattern;
this.$scope.validation.tagValidationPattern = this.TagValidationPattern;
- this.$scope.validation.vendorValidationPattern = this.VendorValidationPattern;
+ this.$scope.validation.VendorReleaseValidationPattern = this.VendorReleaseValidationPattern;
+ this.$scope.validation.VendorNameValidationPattern = this.VendorNameValidationPattern;
+ this.$scope.validation.VendorModelNumberValidationPattern = this.VendorModelNumberValidationPattern;
this.$scope.validation.commentValidationPattern = this.CommentValidationPattern;
this.$scope.validation.projectCodeValidationPattern = this.ProjectCodeValidationPattern;
};
@@ -140,12 +150,6 @@ export class GeneralViewModel {
this.$scope.componentCategories = new componentCategories();
this.$scope.componentCategories.selectedCategory = this.$scope.component.selectedCategory;
- // Workaround to short vendor name to 25 chars
- // Amdocs send 27 chars, and the validation pattern is 25 chars.
- if (this.$scope.component.vendorName) {
- this.$scope.component.vendorName = this.$scope.component.vendorName.substr(0, 25);
- }
-
// Init UIModel
this.$scope.component.tags = _.without(this.$scope.component.tags, this.$scope.component.name);
@@ -202,10 +206,7 @@ export class GeneralViewModel {
};
//TODO remove this after handling contact in UI
- if (this.$scope.component.isProduct() && this.$scope.isCreateMode()) {
- (<Product>this.$scope.component).contacts = [];
- (<Product>this.$scope.component).contacts.push(this.cacheService.get("user").userId);
- } else if (this.$scope.isCreateMode()) {
+ if (this.$scope.isCreateMode()) {
this.$scope.component.contactId = this.cacheService.get("user").userId;
}
@@ -273,6 +274,24 @@ export class GeneralViewModel {
});
};
+ this.$scope.updateIcon = ():void => {
+ this.ModalsHandler.openUpdateIconModal(this.$scope.component).then((isDirty:boolean)=> {
+ if(!this.$scope.isCreateMode()){
+ this.$state.current.data.unsavedChanges = this.$state.current.data.unsavedChanges || isDirty;
+ }
+ }, ()=> {
+ // ERROR
+ });
+ };
+
+ this.$scope.possibleToUpdateIcon = ():boolean => {
+ if(this.$scope.componentCategories.selectedCategory && (!this.$scope.component.isResource() || this.$scope.component.vendorName)){
+ return true;
+ }else{
+ return false;
+ }
+ }
+
this.$scope.validateName = (isInit:boolean):void => {
if (isInit === undefined) {
isInit = false;
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html
index 2ad0cbacd6..d3626803e9 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html
+++ b/catalog-ui/src/app/view-models/workspace/tabs/general/general-view.html
@@ -4,122 +4,121 @@
<div class="w-sdc-form-section-container">
- <!--------------------- IMPORT TOSCA FILE USING BROWSE (ALSO VFC) -------------------->
- <div class="i-sdc-form-item" ng-if="isShowFileBrowse">
- <label class="i-sdc-form-label" data-ng-class="{'required':isCreateMode()}">{{browseFileLabel}}</label>
- <file-upload id="fileUploadElement"
- class="i-sdc-form-input"
- element-name="fileElement"
- element-disabled="{{!isCreateMode()&&!(isEditMode()&&component.resourceType=='VF')}} || {{isViewMode()}}"
- form-element="editForm"
- file-model="component.importedFile"
- on-file-changed-in-directive="uploadFileChangedInGeneralTab"
- extensions="{{importedFileExtension}}"
- default-text="'Browse to select file'"
- data-ng-class="{'error':!(isEditMode()&&component.resourceType=='VF') && (!editForm.fileElement.$valid || !component.importedFile.filename)}"></file-upload>
- </div>
-
- <!--------------------- IMPORT TOSCA FILE USING ONBOARDING -------------------->
- <div class="i-sdc-form-item" ng-if="isShowOnboardingSelectionBrowse">
- <label class="i-sdc-form-label required">Select VSP</label>
- <div class="i-sdc-form-file-upload i-sdc-form-input">
- <span class="i-sdc-form-file-name" data-tests-id="filename">{{(fileModel && fileModel.filename) || importedToscaBrowseFileText}}</span>
- <div class="i-sdc-form-file-upload-x-btn" ng-click="cancel()" data-ng-show="fileModel.filename && fileModel.filename!=='' && elementDisabled!=='true'"></div>
- <input type="button" name="fileElement"/>
- <div class="file-upload-browse-btn" data-ng-click="openOnBoardingModal()" data-tests-id="browseButton">Browse</div>
- </div>
- </div>
-
- <div class="input-error-file-upload" data-ng-show="component.importedFile && (!editForm.fileElement.$valid || !component.importedFile.filename)">
- <!-- editForm.fileElement.$error.required <== Can not use this, because the browse is done from outside for the first time -->
- <span ng-show="!(isEditMode()&&component.resourceType=='VF')&&!component.importedFile.filename" translate="NEW_SERVICE_RESOURCE_ERROR_TOSCA_FILE_REQUIRED"></span><!-- Required -->
- <span ng-show="editForm.fileElement.$error.maxsize" translate="VALIDATION_ERROR_MAX_FILE_SIZE"></span>
- <span ng-show="editForm.fileElement.$error.filetype" translate="NEW_SERVICE_RESOURCE_ERROR_VALID_TOSCA_EXTENSIONS" translate-values="{'extensions': '{{importedFileExtension}}' }"></span>
- <span ng-show="editForm.fileElement.$error.emptyFile" translate="VALIDATION_ERROR_EMPTY_FILE"></span>
- </div>
- <!--------------------- IMPORT TOSCA FILE -------------------->
-
<div class="w-sdc-form-columns-wrapper">
<div class="w-sdc-form-column">
-
- <!--------------------- NAME -------------------->
- <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.componentName)}">
- <label class="i-sdc-form-label required">Name</label>
- <input class="i-sdc-form-input"
- data-ng-class="{'view-mode': isViewMode()}"
- name="componentName"
- data-ng-init="isCreateMode() && validateName(true)"
- data-ng-maxlength="{{component.isProduct()?'25':'50'}}"
- maxlength="{{component.isProduct()?'25':'50'}}"
- data-ng-minlength="{{component.isProduct()?'4':'0'}}"
- minlength="{{component.isProduct()?'4':'0'}}"
- data-ng-model="component.name"
- type="text"
- data-required
- data-ng-model-options="{ debounce: 500 }"
- data-ng-pattern="validation.componentNameValidationPattern"
- data-ng-disabled="component.isAlreadyCertified()"
- data-tests-id="name"
- autofocus
- ng-readonly="isViewMode()"
- />
-
- <div class="input-error" data-ng-show="validateField(editForm.componentName)">
- <span ng-show="editForm.componentName.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_RESOURCE_NAME_REQUIRED"></span>
- <span ng-show="editForm.componentName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '50' }"></span>
- <span ng-show="editForm.componentName.$error.minlength" translate="VALIDATION_ERROR_MIN_LENGTH" translate-values="{'min': '4' }"></span>
- <span ng-show="editForm.componentName.$error.nameExist" translate="NEW_SERVICE_RESOURCE_ERROR_NAME_EXISTS"></span>
- <span ng-show="editForm.componentName.$error.pattern" translate="VALIDATION_ERROR_INVALID_NAME"></span>
+ <div class="upper-general-fields">
+ <div class="selected-icon-container" data-ng-class="{'show-only-on-over':'defaulticon'!=component.icon && !isViewMode()}">
+ <div class="selected-icon-inner-container">
+ <div class="sprite-new update-component-icon" data-ng-click="updateIcon()" data-ng-if="!isViewMode() && possibleToUpdateIcon()"></div>
+ <div class="i-sdc-form-item-suggested-icon large selected-icon {{component.iconSprite}} {{component.icon}}"
+ data-ng-class="{ 'disable': isViewMode() || !possibleToUpdateIcon() }"
+ ng-model="component.icon"
+ tooltips tooltip-content='{{component.icon | translate}}'
+ >
+ </div>
+ </div>
+ </div>
+ <div class="name-and-category-fields">
+ <!--------------------- NAME -------------------->
+ <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.componentName)}">
+ <label class="i-sdc-form-label required">Name</label>
+ <input class="i-sdc-form-input"
+ data-ng-class="{'view-mode': isViewMode()}"
+ name="componentName"
+ data-ng-init="isCreateMode() && validateName(true)"
+ data-ng-maxlength="50"
+ maxlength="50"
+ data-ng-model="component.name"
+ type="text"
+ data-required
+ data-ng-model-options="{ debounce: 500 }"
+ data-ng-pattern="validation.componentNameValidationPattern"
+ data-ng-disabled="component.isAlreadyCertified()"
+ data-tests-id="name"
+ autofocus
+ ng-readonly="isViewMode()"
+ />
+
+ <div class="input-error" data-ng-show="validateField(editForm.componentName)">
+ <span ng-show="editForm.componentName.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_RESOURCE_NAME_REQUIRED"></span>
+ <span ng-show="editForm.componentName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '50' }"></span>
+ <span ng-show="editForm.componentName.$error.minlength" translate="VALIDATION_ERROR_MIN_LENGTH" translate-values="{'min': '4' }"></span>
+ <span ng-show="editForm.componentName.$error.nameExist" translate="NEW_SERVICE_RESOURCE_ERROR_NAME_EXISTS"></span>
+ <span ng-show="editForm.componentName.$error.pattern" translate="VALIDATION_ERROR_INVALID_NAME"></span>
+ </div>
+ </div>
+ <!--------------------- NAME -------------------->
+
+
+
+ <!--------------------- CATEGORIES -------------------->
+ <div class="i-sdc-form-item"
+ data-ng-class="{'error': validateField(editForm.category)}">
+ <loader data-display="!categories && !initCategoreis()" relative="true"></loader>
+ <label class="i-sdc-form-label required">Category</label>
+ <select class="i-sdc-form-select"
+ data-required
+ name="category"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-change="onCategoryChange()"
+ data-ng-disabled="component.isAlreadyCertified() || (component.isCsarComponent() && component.selectedCategory && component.selectedCategory!=='')"
+ data-ng-model="componentCategories.selectedCategory"
+ data-tests-id="selectGeneralCategory"
+ >
+ <option value="">Select category</option>
+ <optgroup ng-if="component.isResource()" data-ng-repeat="mainCategory in categories | orderBy:['name']" label="{{mainCategory.name}}" data-tests-id="{{mainCategory.name}}">
+ <option data-ng-repeat="subCategory in mainCategory.subcategories track by $index"
+ data-ng-selected="componentCategories.selectedCategory === calculateUnique(mainCategory.name,subCategory.name)"
+ data-tests-id="{{subCategory.name}}"
+ value="{{calculateUnique(mainCategory.name, subCategory.name)}}">{{subCategory.name}}
+
+ </option>
+ </optgroup>
+ <option ng-if="component.isService()" data-ng-repeat="mainCategory in categories | orderBy:['name']"
+ data-ng-selected="component.selectedCategory===mainCategory.name"
+ value="{{mainCategory.name}}"
+ data-tests-id="{{mainCategory.name}}">{{mainCategory.name}}</option>
+ </select>
+
+ <div class="input-error" data-ng-show="validateField(editForm.category)">
+ <span ng-show="editForm.category.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_CATEGORY_REQUIRED"></span>
+ </div>
+ </div>
+ <!--------------------- CATEGORIES -------------------->
+ </div>
</div>
- </div>
- <!--------------------- NAME -------------------->
+ <!--------------------- RESOURCE TAGS -------------------->
+ <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.tags)}">
+ <label class="i-sdc-form-label">Tags</label>
- <!--------------------- FULL NAME -------------------->
- <div ng-if="component.isProduct()" class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.fullName)}">
- <label class="i-sdc-form-label required">Full Name</label>
- <input class="i-sdc-form-input"
- name="fullName"
- data-ng-class="{'view-mode': isViewMode()}"
- data-ng-change="validateName()"
- data-ng-maxlength="100"
- maxlength="100"
- data-ng-minlength="4"
- minlength="4"
- data-ng-model="component.fullName"
- type="text"
- data-required
- data-ng-model-options="{ debounce: 500 }"
- data-ng-pattern="validation.commentValidationPattern"
- data-tests-id="fullName"
- autofocus
- ng-readonly="isViewMode()"
- />
+ <sdc-tags form-element="editForm" element-name="tags" max-tags="20" class="i-sdc-form-item-tags"
+ sdc-disabled="isViewMode()"
+ tags="component.tags"
+ pattern="validation.tagValidationPattern"
+ special-tag="component.name"></sdc-tags>
- <div class="input-error" data-ng-show="validateField(editForm.fullName)">
- <span ng-show="editForm.fullName.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_RESOURCE_NAME_REQUIRED"></span>
- <span ng-show="editForm.fullName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '50' }"></span>
- <span ng-show="editForm.fullName.$error.minlength" translate="VALIDATION_ERROR_MIN_LENGTH" translate-values="{'min': '4' }"></span>
- <span ng-show="editForm.fullName.$error.nameExist" translate="NEW_SERVICE_RESOURCE_ERROR_NAME_EXISTS"></span>
- <span ng-show="editForm.fullName.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ <div class="input-error" data-ng-show="validateField(editForm.tags)">
+ <span ng-show="editForm.tags.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ <span ng-show="editForm.tags.$error.nameExist" translate="NEW_SERVICE_RESOURCE_ERROR_TAG_NAME_EXIST"></span>
</div>
</div>
- <!--------------------- NAME -------------------->
+ <!--------------------- RESOURCE TAGS -------------------->
<!--------------------- DESCRIPTION -------------------->
- <div class="i-sdc-form-item"
+ <div class="i-sdc-form-item description-field"
data-ng-class="{'error': validateField(editForm.description)}">
<label class="i-sdc-form-label required">Description</label>
- <textarea class="description"
- name="description"
- data-ng-class="{'view-mode': isViewMode()}"
- data-ng-maxlength="1024"
- data-required
- data-ng-model="component.description"
- data-ng-model-options="{ debounce: 500 }"
- data-ng-pattern="validation.commentValidationPattern"
- maxlength="1024"
- data-tests-id="description"></textarea>
+ <textarea class="description"
+ name="description"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-maxlength="1024"
+ data-required
+ data-ng-model="component.description"
+ data-ng-model-options="{ debounce: 500 }"
+ data-ng-pattern="validation.commentValidationPattern"
+ maxlength="1024"
+ data-tests-id="description"></textarea>
<!-- placeholder="Description here..." -->
<div class="input-error" data-ng-show="validateField(editForm.description)">
@@ -130,110 +129,85 @@
</div>
<!--------------------- DESCRIPTION -------------------->
- <!--------------------- CATEGORIES -------------------->
- <div class="i-sdc-form-item"
- data-ng-class="{'error': validateField(editForm.category)}"
- data-ng-if="!component.isProduct()">
- <loader data-display="!categories && !initCategoreis()" relative="true"></loader>
- <label class="i-sdc-form-label required">Category</label>
- <select class="i-sdc-form-select"
- data-required
- name="category"
- data-ng-class="{'view-mode': isViewMode()}"
- data-ng-change="onCategoryChange()"
- data-ng-disabled="component.isAlreadyCertified() || (component.isCsarComponent() && component.selectedCategory && component.selectedCategory!=='')"
- data-ng-model="componentCategories.selectedCategory"
- data-tests-id="selectGeneralCategory"
- >
- <option value="">Select category</option>
- <optgroup ng-if="component.isResource()" data-ng-repeat="mainCategory in categories | orderBy:['name']" label="{{mainCategory.name}}" data-tests-id="{{mainCategory.name}}">
- <option data-ng-repeat="subCategory in mainCategory.subcategories track by $index"
- data-ng-selected="componentCategories.selectedCategory === calculateUnique(mainCategory.name,subCategory.name)"
- data-tests-id="{{subCategory.name}}"
- value="{{calculateUnique(mainCategory.name, subCategory.name)}}">{{subCategory.name}}
-
- </option>
- </optgroup>
- <option ng-if="component.isService()" data-ng-repeat="mainCategory in categories | orderBy:['name']"
- data-ng-selected="component.selectedCategory===mainCategory.name"
- value="{{mainCategory.name}}"
- data-tests-id="{{mainCategory.name}}">{{mainCategory.name}}</option>
- </select>
-
- <div class="input-error" data-ng-show="validateField(editForm.category)">
- <span ng-show="editForm.category.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_CATEGORY_REQUIRED"></span>
- </div>
- </div>
- <!--------------------- CATEGORIES -------------------->
-
- <!--------------------- PROJECT CODE -------------------->
- <div class="i-sdc-form-item" data-ng-if="!component.isResource()"
- data-ng-class="{'error': validateField(editForm.projectCode)}">
- <label class="i-sdc-form-label required" translate="GENERAL_LABEL_PROJECT_CODE"></label>
- <input class="i-sdc-form-input" type="text"
- data-ng-model="component.projectCode"
- data-ng-class="{'view-mode': isViewMode()}"
- data-ng-model-options="{ debounce: 500 }"
- maxlength="50"
- data-required
- name="projectCode"
- data-ng-pattern="validation.projectCodeValidationPattern"
- data-tests-id="projectCode"
- />
+ </div><!-- Close w-sdc-form-column -->
- <div class="input-error" data-ng-show="validateField(editForm.projectCode)">
- <span ng-show="editForm.projectCode.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_PROJECT_CODE_REQUIRED"></span>
- <span ng-show="editForm.projectCode.$error.pattern" translate="NEW_SERVICE_RESOURCE_ERROR_PROJECT_CODE_NOT_VALID"></span>
+ <div class="w-sdc-form-column">
+ <!--------------------- IMPORT TOSCA FILE USING BROWSE (ALSO VFC) -------------------->
+ <div class="i-sdc-form-item" ng-if="isShowFileBrowse">
+ <label class="i-sdc-form-label" data-ng-class="{'required':isCreateMode()}">{{browseFileLabel}}</label>
+ <file-upload id="fileUploadElement"
+ class="i-sdc-form-input"
+ element-name="fileElement"
+ element-disabled="{{!isCreateMode()&&!(isEditMode()&&component.resourceType=='VF')}} || {{isViewMode()}}"
+ form-element="editForm"
+ file-model="component.importedFile"
+ on-file-changed-in-directive="uploadFileChangedInGeneralTab"
+ extensions="{{importedFileExtension}}"
+ default-text="'Browse to select file'"
+ data-ng-class="{'error':!(isEditMode()&&component.resourceType=='VF') && (!editForm.fileElement.$valid || !component.importedFile.filename)}"></file-upload>
</div>
- </div>
+ <!--------------------- IMPORT TOSCA FILE USING ONBOARDING -------------------->
+ <div class="i-sdc-form-item" ng-if="isShowOnboardingSelectionBrowse">
+ <label class="i-sdc-form-label required">Select VSP</label>
+ <div class="i-sdc-form-file-upload i-sdc-form-input">
+ <span class="i-sdc-form-file-name" data-tests-id="filename">{{(fileModel && fileModel.filename) || importedToscaBrowseFileText}}</span>
+ <div class="i-sdc-form-file-upload-x-btn" ng-click="cancel()" data-ng-show="fileModel.filename && fileModel.filename!=='' && elementDisabled!=='true'"></div>
+ <input type="button" name="fileElement"/>
+ <div class="file-upload-browse-btn" data-ng-click="openOnBoardingModal()" data-tests-id="browseButton">Browse</div>
+ </div>
+ </div>
- <!--------------------- ECOMPGENERATEDNAMING -------------------->
+ <div class="input-error-file-upload" data-ng-show="component.importedFile && (!editForm.fileElement.$valid || !component.importedFile.filename)">
+ <!-- editForm.fileElement.$error.required <== Can not use this, because the browse is done from outside for the first time -->
+ <span ng-show="!(isEditMode()&&component.resourceType=='VF')&&!component.importedFile.filename" translate="NEW_SERVICE_RESOURCE_ERROR_TOSCA_FILE_REQUIRED"></span><!-- Required -->
+ <span ng-show="editForm.fileElement.$error.maxsize" translate="VALIDATION_ERROR_MAX_FILE_SIZE"></span>
+ <span ng-show="editForm.fileElement.$error.filetype" translate="NEW_SERVICE_RESOURCE_ERROR_VALID_TOSCA_EXTENSIONS" translate-values="{'extensions': '{{importedFileExtension}}' }"></span>
+ <span ng-show="editForm.fileElement.$error.emptyFile" translate="VALIDATION_ERROR_EMPTY_FILE"></span>
+ </div>
+ <!--------------------- IMPORT TOSCA FILE -------------------->
- <div class="i-sdc-form-item"
- data-ng-class="{'error': validateField(editForm.ecompGeneratedNaming)}"
- data-ng-if="component.isService()">
- <label class="i-sdc-form-label">Ecomp Generated Naming</label>
- <select class="i-sdc-form-select"
- data-required
- name="ecompGeneratedNaming"
- data-ng-change="onEcompGeneratedNamingChange()"
- data-ng-class="{'view-mode': isViewMode()}"
- data-ng-model="component.ecompGeneratedNaming"
- data-tests-id="ecompGeneratedNaming">
- <option ng-value="true">true</option>
- <option ng-value="false">false</option>
- </select>
- <div class="input-error" data-ng-show="validateField(editForm.ecompGeneratedNaming)">
+ <!--------------------- USER ID -------------------->
+ <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.contactId)}">
+ <label class="i-sdc-form-label required" translate="GENERAL_LABEL_CONTACT_ID"></label>
+ <input class="i-sdc-form-input" type="text"
+ data-ng-model="component.contactId"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-required="true"
+ name="contactId"
+ data-ng-pattern="validation.contactIdValidationPattern"
+ data-ng-model-options="{ debounce: 500 }"
+ data-tests-id="contactId"
+ maxlength="50"
+ />
+ <div class="input-error" data-ng-show="validateField(editForm.contactId)">
+ <span ng-show="editForm.contactId.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_CONTACT_REQUIRED"></span>
+ <span ng-show="editForm.contactId.$error.pattern" translate="NEW_SERVICE_RESOURCE_ERROR_CONTACT_NOT_VALID"></span>
</div>
</div>
- <!--------------------- CATEGORIES -------------------->
-
- <!--------------------- NAMING POLICY -------------------->
- <div ng-if="component.isService()" class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.namingPolicy)}">
- <label class="i-sdc-form-label">Naming policy</label>
- <input class="i-sdc-form-input"
- name="fullName"
- data-ng-class="{'view-mode': isViewMode() || !component.ecompGeneratedNaming}"
- data-ng-maxlength="100"
- maxlength="100"
- data-ng-model="component.namingPolicy"
- type="text"
+ <!--------------------- USER ID -------------------->
+
+ <!--------------------- PROJECT CODE -------------------->
+ <div class="i-sdc-form-item" data-ng-if="!component.isResource()"
+ data-ng-class="{'error': validateField(editForm.projectCode)}">
+ <label class="i-sdc-form-label required" translate="GENERAL_LABEL_PROJECT_CODE"></label>
+ <input class="i-sdc-form-input" type="text"
+ data-ng-model="component.projectCode"
+ data-ng-class="{'view-mode': isViewMode()}"
data-ng-model-options="{ debounce: 500 }"
- data-ng-pattern="validation.commentValidationPattern"
- data-tests-id="namingPolicy"
- autofocus
- ng-readonly="isViewMode() || !component.ecompGeneratedNaming"
+ maxlength="50"
+ data-required
+ name="projectCode"
+ data-ng-pattern="validation.projectCodeValidationPattern"
+ data-tests-id="projectCode"
/>
- <div class="input-error" data-ng-show="validateField(editForm.namingPolicy)">
- <span ng-show="editForm.namingPolicy.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '100' }"></span>
- <span ng-show="editForm.namingPolicy.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ <div class="input-error" data-ng-show="validateField(editForm.projectCode)">
+ <span ng-show="editForm.projectCode.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_PROJECT_CODE_REQUIRED"></span>
+ <span ng-show="editForm.projectCode.$error.pattern" translate="NEW_SERVICE_RESOURCE_ERROR_PROJECT_CODE_NOT_VALID"></span>
</div>
</div>
- <!--------------------- NAMING POLICY -------------------->
-
<!--------------------- VENDOR NAME -------------------->
<div ng-if="component.isResource()" class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.vendorName)}">
@@ -242,20 +216,20 @@
data-ng-class="{'view-mode': isViewMode()}"
data-ng-model="component.vendorName"
data-ng-model-options="{ debounce: 500 }"
- data-ng-maxlength="25"
+ data-ng-maxlength="60"
data-required
ng-click="oldValue = component.vendorName"
name="vendorName"
data-ng-change="onVendorNameChange(oldValue)"
- data-ng-pattern="validation.vendorValidationPattern"
- maxlength="25"
+ data-ng-pattern="validation.VendorNameValidationPattern"
+ maxlength="60"
data-ng-disabled="component.isAlreadyCertified() || (component.isCsarComponent() && component.vendorName && component.vendorName!=='')"
data-tests-id="vendorName"
- />
+ />
<div class="input-error" data-ng-show="validateField(editForm.vendorName)">
<span ng-show="editForm.vendorName.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_VENDOR_NAME_REQUIRED"></span>
- <span ng-show="editForm.vendorName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '25' }"></span>
+ <span ng-show="editForm.vendorName.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '60' }"></span>
<span ng-show="editForm.vendorName.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
</div>
@@ -275,80 +249,160 @@
data-ng-maxlength="25"
data-required
name="vendorRelease"
- data-ng-pattern="validation.vendorValidationPattern"
+ data-ng-pattern="validation.VendorReleaseValidationPattern"
maxlength="25"
data-ng-disabled="component.isCsarComponent() && component.vendorRelease && component.vendorRelease!==''"
data-tests-id="vendorRelease"
- />
+ />
<div class="input-error" data-ng-show="validateField(editForm.vendorRelease)">
<span ng-show="editForm.vendorRelease.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_VENDOR_RELEASE_REQUIRED"></span>
- <span ng-show="editForm.vendorRelease.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '128' }"></span>
+ <span ng-show="editForm.vendorRelease.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '25' }"></span>
<span ng-show="editForm.vendorRelease.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
</div>
</div>
<!--------------------- VENDOR RELEASE -------------------->
+ <!--------------------- Resource Model Number -------------------->
+ <div ng-if="component.isResource()"
+ class="i-sdc-form-item"
+ data-ng-class="{'error': validateField(editForm.resourceVendorModelNumber)}">
+ <label class="i-sdc-form-label" translate="GENERAL_TAB_LABEL_RESOURCE_MODEL_NUMBER"></label>
+ <input class="i-sdc-form-input" type="text"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-model="component.resourceVendorModelNumber"
+ data-ng-model-options="{ debounce: 500 }"
+ data-ng-maxlength="65"
+ name="resourceVendorModelNumber"
+ data-ng-pattern="validation.VendorModelNumberValidationPattern"
+ maxlength="65"
+ data-tests-id="resourceVendorModelNumber"
+ />
+ <div class="input-error" data-ng-show="validateField(editForm.resourceVendorModelNumber)">
+ <span ng-show="editForm.resourceVendorModelNumber.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '65' }"></span>
+ <span ng-show="editForm.resourceVendorModelNumber.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ </div>
+ </div>
+ <!--------------------- Resource Model Number -------------------->
- </div><!-- Close w-sdc-form-column -->
-
- <div class="w-sdc-form-column">
-
- <!--------------------- RESOURCE TAGS -------------------->
- <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.tags)}">
- <label class="i-sdc-form-label">Tags</label>
+ <!--------------------- ECOMPGENERATEDNAMING -------------------->
- <sdc-tags form-element="editForm" element-name="tags" max-tags="20" class="i-sdc-form-item-tags"
- sdc-disabled="isViewMode()"
- tags="component.tags"
- pattern="validation.tagValidationPattern"
- special-tag="component.name"></sdc-tags>
+ <div class="i-sdc-form-item"
+ data-ng-class="{'error': validateField(editForm.ecompGeneratedNaming)}"
+ data-ng-if="component.isService()">
+ <label class="i-sdc-form-label">Ecomp Generated Naming</label>
+ <select class="i-sdc-form-select"
+ data-required
+ name="ecompGeneratedNaming"
+ data-ng-change="onEcompGeneratedNamingChange()"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-model="component.ecompGeneratedNaming"
+ data-tests-id="ecompGeneratedNaming">
+ <option ng-value="true">true</option>
+ <option ng-value="false">false</option>
+ </select>
+ <div class="input-error" data-ng-show="validateField(editForm.ecompGeneratedNaming)">
- <div class="input-error" data-ng-show="validateField(editForm.tags)">
- <span ng-show="editForm.tags.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
- <span ng-show="editForm.tags.$error.nameExist" translate="NEW_SERVICE_RESOURCE_ERROR_TAG_NAME_EXIST"></span>
+ </div>
</div>
- </div>
- <!--------------------- RESOURCE TAGS -------------------->
+ <!--------------------- CATEGORIES -------------------->
- <!--------------------- USER ID -------------------->
- <div class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.contactId)}">
- <label class="i-sdc-form-label " data-ng-class="{'required':!component.isProduct()}" translate="GENERAL_LABEL_CONTACT_ID"></label>
- <input class="i-sdc-form-input" type="text" data-ng-if="!component.isProduct()"
- data-ng-model="component.contactId"
- data-ng-class="{'view-mode': isViewMode()}"
- data-ng-required="!component.isProduct()"
- name="contactId"
- data-ng-pattern="validation.contactIdValidationPattern"
- data-ng-model-options="{ debounce: 500 }"
- data-tests-id="contactId"
- maxlength="50"
+ <!--------------------- NAMING POLICY -------------------->
+ <div ng-if="component.isService()" class="i-sdc-form-item" data-ng-class="{'error': validateField(editForm.namingPolicy)}">
+ <label class="i-sdc-form-label">Naming policy</label>
+ <input class="i-sdc-form-input"
+ name="fullName"
+ data-ng-class="{'view-mode': isViewMode() || !component.ecompGeneratedNaming}"
+ data-ng-maxlength="100"
+ maxlength="100"
+ data-ng-model="component.namingPolicy"
+ type="text"
+ data-ng-model-options="{ debounce: 500 }"
+ data-ng-pattern="validation.commentValidationPattern"
+ data-tests-id="namingPolicy"
+ autofocus
+ ng-readonly="isViewMode() || !component.ecompGeneratedNaming"
/>
- <input class="i-sdc-form-input" type="text" data-ng-if="component.isProduct()"
- data-ng-model="component.contacts[0]"
- data-ng-class="{'view-mode': isViewMode()}"
- data-ng-required="!component.isProduct()"
- name="contactId"
- data-ng-pattern="validation.contactIdValidationPattern"
- data-ng-model-options="{ debounce: 500 }"
- data-tests-id="contactId"
- maxlength="50"
- />
- <div class="input-error" data-ng-show="validateField(editForm.contactId)">
- <span ng-show="editForm.contactId.$error.required" translate="NEW_SERVICE_RESOURCE_ERROR_CONTACT_REQUIRED"></span>
- <span ng-show="editForm.contactId.$error.pattern" translate="NEW_SERVICE_RESOURCE_ERROR_CONTACT_NOT_VALID"></span>
+ <div class="input-error" data-ng-show="validateField(editForm.namingPolicy)">
+ <span ng-show="editForm.namingPolicy.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '100' }"></span>
+ <span ng-show="editForm.namingPolicy.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ </div>
</div>
- </div>
- <!--------------------- USER ID -------------------->
-
+ <!--------------------- NAMING POLICY -------------------->
+ <!--------------------- Service Type -------------------->
+ <div ng-if="component.isService()"
+ class="i-sdc-form-item"
+ data-ng-class="{'error': validateField(editForm.serviceType)}">
+ <label class="i-sdc-form-label" translate="GENERAL_TAB_LABEL_SERVICE_TYPE"></label>
+ <input class="i-sdc-form-input" type="text"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-model="component.serviceType"
+ data-ng-model-options="{ debounce: 500 }"
+ name="serviceType"
+ data-tests-id="serviceType"
+ data-ng-maxlength="25"
+ data-ng-pattern="validation.VendorReleaseValidationPattern"
+ maxlength="25"
+ />
+ <div class="input-error" data-ng-show="validateField(editForm.serviceType)">
+ <span ng-show="editForm.serviceType.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '25' }"></span>
+ <span ng-show="editForm.serviceType.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ </div>
+ </div>
+ <!--------------------- Service Type -------------------->
+
+ <!--------------------- Service Role -------------------->
+ <div ng-if="component.isService()"
+ class="i-sdc-form-item"
+ data-ng-class="{'error': validateField(editForm.serviceRole)}">
+ <label class="i-sdc-form-label" translate="GENERAL_TAB_LABEL_SERVICE_ROLE"></label>
+ <input class="i-sdc-form-input" type="text"
+ data-ng-class="{'view-mode': isViewMode()}"
+ data-ng-model="component.serviceRole"
+ data-ng-model-options="{ debounce: 500 }"
+ name="serviceRole"
+ data-tests-id="serviceRole"
+ data-ng-maxlength="25"
+ data-ng-pattern="validation.VendorReleaseValidationPattern"
+ maxlength="25"
+ />
+ <div class="input-error" data-ng-show="validateField(editForm.serviceRole)">
+ <span ng-show="editForm.serviceRole.$error.maxlength" translate="VALIDATION_ERROR_MAX_LENGTH" translate-values="{'max': '25' }"></span>
+ <span ng-show="editForm.serviceRole.$error.pattern" translate="VALIDATION_ERROR_SPECIAL_CHARS_NOT_ALLOWED"></span>
+ </div>
+ </div>
+ <!--------------------- Service Role -------------------->
+ <div class="meta-data" data-ng-if="component.creationDate">
+ <div>
+ <b>Created:</b>
+ </div>
+ <div class="meta-data-item-value">{{component.creationDate | date:'MM/dd/yyyy'}}, {{component.creatorFullName}}</div>
+ <div>
+ <b>Modifed:</b>
+ </div>
+ <div class="meta-data-item-value">
+ {{component.lastUpdateDate | date:'MM/dd/yyyy'}}
+ </div>
+ <div>
+ <b>UUID:</b>
+ </div>
+ <div class="meta-data-item-value">
+ {{component.uuid}}
+ </div>
+ <div>
+ <b>Invariant UUID:</b>
+ </div>
+ <div class="meta-data-item-value">
+ {{component.invariantUUID}}
+ </div>
+ </div>
</div><!-- Close w-sdc-form-column -->
</div>
</div><!-- Close w-sdc-form-section-container -->
</form>
-
</div>
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/general/general.less b/catalog-ui/src/app/view-models/workspace/tabs/general/general.less
index caa755cce3..9633ec5bb6 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/general/general.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/general/general.less
@@ -1,8 +1,8 @@
.sdc-workspace-general-step {
-
+ display: flex;
.w-sdc-form {
padding: 0;
-
+ flex-grow: 10;
.i-sdc-form-file-upload{
input[type="button"] {
cursor: pointer;
@@ -33,6 +33,14 @@
}
}
+ .description{
+ height: 300px;
+ }
+
+ .i-sdc-form-item.description-field{
+ margin-bottom: 0;
+ }
+
.w-sdc-form-section-container {
text-align: center;
}
@@ -43,6 +51,7 @@
width: auto;
padding: 10px;
}
+ margin-bottom: 15px;
}
.i-sdc-form-label {
@@ -63,6 +72,73 @@
}
+ .w-sdc-form-column {
+ position: relative;
+ }
+
+ .meta-data{
+ padding: 8px 0 2px 20px;
+ text-align: left;
+ background-color: @tlv_color_t;
+ position: absolute;
+ bottom: 0;
+ width: 100%;
+ .meta-data-item-value{
+ padding-bottom: 6px;
+ }
+ }
+
+ .upper-general-fields{
+ display: flex;
+ }
+
+ .selected-icon-container{
+ flex-grow: 1;
+ display: flex;
+ align-items: center;
+ .selected-icon-inner-container{
+ height: 64px;
+ width: 64px;
+ margin: 0 auto;
+ }
+ .update-component-icon{
+ position: relative;
+ float: right;
+ cursor: pointer;
+ }
+ .selected-icon{
+ position: relative;
+ top: -20px;
+ z-index: -1;
+ &.disable{
+ position: inherit;
+ }
+ }
+ &.show-only-on-over{
+ .update-component-icon{
+ display: none;
+ }
+ .selected-icon{
+ position: inherit;
+ }
+ &:hover{
+ .update-component-icon{
+ display: inline-block;
+ }
+ .selected-icon{
+ position: relative;
+ }
+ }
+ }
+ }
+
+ .name-and-category-fields{
+ flex-grow: 5;
+ }
+
+
+
+
}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/icons/icons-view.html b/catalog-ui/src/app/view-models/workspace/tabs/icons/icons-view.html
deleted file mode 100644
index aac14e0e84..0000000000
--- a/catalog-ui/src/app/view-models/workspace/tabs/icons/icons-view.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<div class="workspace-icons">
-
- <form novalidate class="w-sdc-form" name="iconForm">
- <label class="i-sdc-form-label icons-label required">Icons</label>
- <div class="selected-icon-container" data-ng-class="{'view-mode': isViewMode()}">
- <div class="i-sdc-form-item-suggested-icon large selected-icon {{iconSprite}} {{component.icon}}"
- data-ng-class="{ 'disable': isViewMode() }"
- ng-model="component.icon"
- tooltips tooltip-content='{{component.icon | translate}}'
- >
- </div>
- </div>
- <div data-ng-class="{'view-mode': isViewMode()}" class="icons-text">Select one of the icons below for the asset</div>
- <div class="i-sdc-form-item suggested-icons-container" data-ng-class="{'view-mode no-pointer-events' : isViewMode()}">
- <div class ="suggested-icon-wrapper" ng-class="component.icon==='{{iconSrc}}' ? 'selected' : '' " data-ng-repeat="iconSrc in icons track by $index">
- <div class="i-sdc-form-item-suggested-icon large {{iconSprite}} {{iconSrc}}" data-ng-class="component.isAlreadyCertified() || isViewMode() ? 'disable':'hand'"
- ng-model="component.icon"
- data-tests-id="{{iconSrc}} iconBox"
- data-ng-click="!component.isAlreadyCertified() && setComponentIcon(iconSrc)"
- tooltips tooltip-content='{{iconSrc | translate}}'
- >
- </div>
- </div>
- </div>
- </form>
-</div>
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/icons/icons.less b/catalog-ui/src/app/view-models/workspace/tabs/icons/icons.less
deleted file mode 100644
index 65f946f395..0000000000
--- a/catalog-ui/src/app/view-models/workspace/tabs/icons/icons.less
+++ /dev/null
@@ -1,65 +0,0 @@
-.workspace-icons {
-
- width: 89%;
- display: inline-block;
- text-align: center;
- align-items: center;
-
- .w-sdc-form {
- padding-top: 0px;
- padding-bottom: 0px;
- .selected-icon-container {
- text-align: left;
- border: 1px solid #cfcfcf;
- clear: both;
- margin-bottom: 30px;
- padding: 2px 0px 5px 5px;
- .selected-icon {
- margin: 8px 5px 0px 6px;
- }
- }
-
- .suggested-icons-container {
- text-align: left;
- border: 1px solid #cfcfcf;
- clear: both;
- padding: 2px 0px 5px 5px;
- height: 340px;
- margin-bottom: 0px;
-
- .suggested-icon-wrapper {
- margin: 8px 5px 0px 6px;
- display: inline-block;
-
- &.selected {
- border: 2px solid @main_color_a;
- border-radius: 35px;
- display: inline-block;
- line-height: 0px;
- padding: 3px;
- }
-
- }
- .suggested-icon {
- // margin: 8px 5px 0px 6px;
- display: inline-block;
- &.disable{
- opacity: 0.4;
- }
- }
- }
-
- .icons-label {
- float: left;
- }
-
- .icons-text {
- text-align: left;
- line-height: 32px;
- padding-left: 10px;
- width: 100%;
- border: 1px solid #cfcfcf;
- border-bottom: none;
- }
- }
-}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts.less b/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts.less
index 3ba9cf47d5..5e69c44e9b 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/information-artifacts/information-artifacts.less
@@ -12,7 +12,7 @@
}
.table-container-flex {
- margin-top: 27px;
+ margin-top: 0;
.item-opened{
word-wrap: break-word;
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/inputs/inputs.less b/catalog-ui/src/app/view-models/workspace/tabs/inputs/inputs.less
index eff5c5395b..17c18e1741 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/inputs/inputs.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/inputs/inputs.less
@@ -216,7 +216,7 @@
}
.table-container-flex {
- margin-top: 27px;
+ margin-top: 0;
width: 46%;
min-width: 46%;
display: inline-block;
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model.ts b/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model.ts
deleted file mode 100644
index c891875f52..0000000000
--- a/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view-model.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * SDC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-'use strict';
-import {ComponentFactory} from "app/utils";
-import {Product, IGroup, ISubCategory, IMainCategory} from "app/models";
-import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
-import {CacheService} from "app/services";
-
-export interface IProductHierarchyScope extends IWorkspaceViewModelScope {
-
- categoriesOptions:Array<IMainCategory>;
- product:Product;
- isLoading:boolean;
- showDropDown:boolean;
-
- onInputTextClicked():void;
- onGroupSelected(category:IMainCategory, subcategory:ISubCategory, group:IGroup):void;
- clickOutside():void;
- deleteGroup(uniqueId:string):void;
-}
-
-export class ProductHierarchyViewModel {
-
- static '$inject' = [
- '$scope',
- 'Sdc.Services.CacheService',
- 'ComponentFactory',
- '$state'
- ];
-
- constructor(private $scope:IProductHierarchyScope,
- private cacheService:CacheService,
- private ComponentFactory:ComponentFactory,
- private $state:ng.ui.IStateService) {
-
-
- this.$scope.product = <Product>this.$scope.getComponent();
- this.$scope.setValidState(true);
- this.initScope();
- this.$scope.updateSelectedMenuItem();
- }
-
- private initCategories = () => {
- this.$scope.categoriesOptions = angular.copy(this.cacheService.get('productCategories'));
- let selectedGroup:Array<IGroup> = [];
- _.forEach(this.$scope.product.categories, (category:IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:ISubCategory) => {
- selectedGroup = selectedGroup.concat(subcategory.groupings);
- });
- });
- _.forEach(this.$scope.categoriesOptions, (category:IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:ISubCategory) => {
- _.forEach(subcategory.groupings, (group:ISubCategory) => {
- let componentGroup:IGroup = _.find(selectedGroup, (componentGroupObj) => {
- return componentGroupObj.uniqueId == group.uniqueId;
- });
- if (componentGroup) {
- group.isDisabled = true;
- }
- });
- });
- });
- };
-
- private setFormValidation = ():void => {
-
- this.$scope.setValidState(true);
-
- };
-
- private initScope = ():void => {
- this.$scope.isLoading = false;
- this.$scope.showDropDown = false;
- this.initCategories();
- this.setFormValidation();
-
- this.$scope.onGroupSelected = (category:IMainCategory, subcategory:ISubCategory, group:IGroup):void => {
- this.$scope.product.addGroup(category, subcategory, group);
- this.$state.current.data.unsavedChanges = !this.$scope.isViewMode();
- group.isDisabled = true;
- this.$scope.showDropDown = false;
- this.setFormValidation();
- };
-
- this.$scope.onInputTextClicked = ():void => {//just edit the component in place, no pop up nor server update ?
- this.$scope.showDropDown = !this.$scope.showDropDown;
- };
-
- this.$scope.clickOutside = ():any => {
- this.$scope.showDropDown = false;
- };
-
- this.$scope.deleteGroup = (uniqueId:string):void => {
- //delete group from component
- this.$scope.product.deleteGroup(uniqueId);
- this.$state.current.data.unsavedChanges = !this.$scope.isViewMode();
- this.setFormValidation();
- //enabled group
- _.forEach(this.$scope.categoriesOptions, (category:IMainCategory) => {
- _.forEach(category.subcategories, (subcategory:ISubCategory) => {
- let groupObj:IGroup = _.find(subcategory.groupings, (group) => {
- return group.uniqueId === uniqueId;
- });
- if (groupObj) {
- groupObj.isDisabled = false;
- }
- });
- });
- }
- };
-}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view.html b/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view.html
deleted file mode 100644
index 2335ad7c74..0000000000
--- a/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy-view.html
+++ /dev/null
@@ -1,40 +0,0 @@
-<div class="workspace-hierarchy">
- <div class="dropdown-container" clicked-outside="{onClickedOutside: 'clickOutside()', clickedOutsideEnable: 'true'}" >
- <input placeholder="Add Group" data-ng-click="onInputTextClicked()" class="dropdown-input-text" data-ng-model="search.filterTerms" data-ng-disabled="isViewMode()" data-ng-class="{'view-mode': isViewMode()}" data-ng-model-options="{debounce: 200}"/>
- <div data-ng-class="{'show': showDropDown}" class="dropdown-content" >
- <perfect-scrollbar scroll-y-margin-offset="0" include-padding="false" class="scrollbar-container">
- <div ng-repeat="category in categoriesOptions track by $index">
- <div ng-repeat="subcategory in category.subcategories track by $index">
- <div class="dropdown-option" ng-show="!category.filteredGroup || category.filteredGroup.length > 0">
- <div class="category-container">
- <div class="category">{{category.name}}</div>
- <div class="subcategory">{{subcategory.name}}</div>
- </div>
- <div class="groupings-container">
- <div ng-init="group.filterTerms = group.name + ' ' + category.name + ' ' + subcategory.name"
- ng-repeat="group in (category.filteredGroup = (subcategory.groupings | filter:search )) track by $index">
- <div class="group" data-ng-disabled="group.isDisabled" data-ng-class="{'disabled-group': group.isDisabled}" ng-click="onGroupSelected(category, subcategory, group)">
- <span >{{group.name}}</span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </perfect-scrollbar>
- </div>
- </div>
- <div class="hierarchy-groups-container no-border-top" data-ng-class="{'view-mode': isViewMode()}">
- <perfect-scrollbar scroll-y-margin-offset="0" include-padding="true" class="scrollbar-container">
- <div ng-if="!product.categories.length || product.categories.length === 0" class="no-groups-text" translate="NEW_PRODUCT_NO_CATEGORIES_TO_DISPLAY"></div>
- <div ng-repeat="category in product.categories track by $index">
- <div ng-repeat="subcategory in category.subcategories track by $index">
- <div class="group-tag" ng-repeat="group in subcategory.groupings track by $index"
- data-ng-init="tooltip = '<b>' + category.name + '</b><br />' + subcategory.name">
- <sdc-tag sdc-disable="isViewMode()" data-on-delete="deleteGroup(uniqueId)" data-tag-data="{tag: group.name, tooltip: tooltip, id: group.uniqueId }"></sdc-tag>
- </div>
- </div>
- </div>
- </perfect-scrollbar>
- </div>
-</div>
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy.less b/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy.less
deleted file mode 100644
index c992558ed2..0000000000
--- a/catalog-ui/src/app/view-models/workspace/tabs/product-hierarchy/product-hierarchy.less
+++ /dev/null
@@ -1,130 +0,0 @@
-.workspace-hierarchy {
- display: inline-block;
- width: 93%;
-
- .scrollbar-container{
- max-height:400px;
- .perfect-scrollbar;
- }
-
- .dropdown-container {
- position: relative;
- display: inline-block;
- width: 100%;
-
- &:after{
- top: 47%;
- right: 1%;
- border: solid transparent;
- content: " ";
- height: 0;
- width: 0;
- position: absolute;
- pointer-events: none;
- border-color: rgba(0, 0, 0, 0);
- border-top-color: black;
- border-width: 4px;
- margin-left: -4px;
- }
-
- .dropdown-input-text {
- width: 100%;
- padding: 4px 10px;
- }
-
- .dropdown-content {
- .perfect-scrollbar;
- border: 1px solid #d8d8d8;
- display: none;
- position: absolute;
- overflow: hidden;
- width: 100%;
- .bg_c;
- max-height: 400px;
- z-index: 999999;
-
- .dropdown-option {
- border-bottom: 1px solid #d8d8d8;
- display: inline-block;
- width: 100%;
- }
-
- .category-container{
- width: 250px;
- float: left;
- padding-left: 5px;
-
- .category {
- .bold;
- padding: 3px 3px 2px 3px;
- &:after{
- .sprite;
- .arrow-left;
- content: '';
- margin-left: 5px;
- transform: rotate(180deg);
- }
- }
- .subcategory {
- padding-left: 3px;
- }
- }
-
- .groupings-container{
- display: inline-block;
- width: 424px;
- border-left: 1px solid #d8d8d8;
- min-height: 55px;
- .group{
- padding: 3px 3px 3px 10px;
- &:hover{
- .hand;
- .bg_n;
- }
- &.disabled-group {
- opacity: 0.5;
- &:hover{
- cursor: auto;
- .bg_c;
- }
- }
- }
- }
-
- .seperator {
- height: 1px;
- width: 100%;
- .bg_j;
- margin: 5px 0px;
- }
- }
- .show {
- display: block;
- }
- }
-
- .hierarchy-groups-container{
- .b_9;
- width: 100%;
- border: 1px solid #d8d8d8;
- height: 425px;
- padding: 15px;
- text-align: center;
-
- .scrollbar-container {
- z-index: 0;
- }
-
- .no-group-text{
- text-align: center;
- margin-top:25px;
- a {
- cursor: pointer;
- }
- }
- .group-tag{
- display: inline-block;
- float: left;
- }
- }
-}
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/properties/properties.less b/catalog-ui/src/app/view-models/workspace/tabs/properties/properties.less
index 3e8d6c3fbd..48c462e143 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/properties/properties.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/properties/properties.less
@@ -76,7 +76,7 @@
}
.table-container-flex {
- margin-top: 27px;
+ margin-top: 0;
.text{
overflow: hidden;
diff --git a/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less b/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less
index 6dfec2980f..23be3c3548 100644
--- a/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less
+++ b/catalog-ui/src/app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less
@@ -1,5 +1,5 @@
.workspace-tosca-artifact {
- width: 93%;
+ width: 100%;
display: inline-block;
.w-sdc-classic-btn {
float: right;
@@ -18,8 +18,7 @@
.table-container-flex {
- margin-top: 27px;
-
+ margin-top: 0;
.item-opened{
word-wrap: break-word;
}
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 21bd199aac..ec8b04dbdb 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
@@ -77,7 +77,6 @@ export interface IWorkspaceViewModelScope extends ng.IScope {
changeLifecycleState(state:string):void;
enabledTabs():void
isDesigner():boolean;
- isProductManager():boolean;
isViewMode():boolean;
isEditMode():boolean;
isCreateMode():boolean;
@@ -91,6 +90,7 @@ export interface IWorkspaceViewModelScope extends ng.IScope {
updateSelectedMenuItem():void;
uploadFileChangedInGeneralTab():void;
updateMenuComponentName(ComponentName:string):void;
+ getTabTitle():string;
reload(component:Component):void;
}
@@ -149,9 +149,6 @@ export class WorkspaceViewModel {
} else {
if (this.$scope.component.lifecycleState === ComponentState.NOT_CERTIFIED_CHECKOUT &&
this.$scope.component.lastUpdaterUserId === this.cacheService.get("user").userId) {
- if (this.$scope.component.isProduct() && this.role == Role.PRODUCT_MANAGER) {
- mode = WorkspaceMode.EDIT;
- }
if ((this.$scope.component.isService() || this.$scope.component.isResource()) && this.role == Role.DESIGNER) {
mode = WorkspaceMode.EDIT;
}
@@ -171,7 +168,7 @@ export class WorkspaceViewModel {
};
private initLeftPalette = ():void => {
- this.LeftPaletteLoaderService.loadLeftPanel(this.$scope.component.componentType);
+ this.LeftPaletteLoaderService.loadLeftPanel(this.$scope.component);
};
private initScope = ():void => {
@@ -192,7 +189,7 @@ export class WorkspaceViewModel {
this.$scope.$state = this.$state;
this.$scope.isLoading = false;
this.$scope.isComposition = (this.$state.current.name.indexOf(States.WORKSPACE_COMPOSITION) > -1);
- this.$scope.isDeployment = (this.$state.current.name.indexOf(States.WORKSPACE_DEPLOYMENT) > -1);
+ this.$scope.isDeployment = this.$state.current.name == States.WORKSPACE_DEPLOYMENT;
this.$scope.progressService = this.progressService;
this.$scope.getComponent = ():Component => {
@@ -269,7 +266,7 @@ export class WorkspaceViewModel {
type: this.$scope.componentType.toLowerCase(),
mode: WorkspaceMode.VIEW,
components: this.$state.params['components']
- },{reload: true});
+ }, {reload: true});
};
@@ -431,7 +428,7 @@ export class WorkspaceViewModel {
switch (url) {
case 'lifecycleState/CHECKOUT':
// only checkOut get the full component from server
- // this.$scope.component = component;
+ // this.$scope.component = component;
// Work around to change the csar version
if (this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG)) {
(<Resource>this.$scope.component).csarVersion = this.cacheService.get(CHANGE_COMPONENT_CSAR_VERSION_FLAG);
@@ -565,18 +562,13 @@ export class WorkspaceViewModel {
return this.role == Role.DESIGNER;
};
- this.$scope.isProductManager = ():boolean => {
- return this.role == Role.PRODUCT_MANAGER;
- };
-
this.$scope.isDisableMode = ():boolean => {
return this.$scope.mode === WorkspaceMode.VIEW && this.$scope.component.lifecycleState === ComponentState.NOT_CERTIFIED_CHECKIN;
};
this.$scope.showFullIcons = ():boolean => {
- //we show revert and save icons only in general\icon view
- return this.$state.current.name === States.WORKSPACE_GENERAL ||
- this.$state.current.name === States.WORKSPACE_ICONS;
+ //we show revert and save icons only in general view
+ return this.$state.current.name === States.WORKSPACE_GENERAL;
};
this.$scope.isCreateMode = ():boolean => {
@@ -593,8 +585,7 @@ export class WorkspaceViewModel {
};
this.$scope.showLifecycleIcon = ():boolean => {
- return this.role == Role.DESIGNER ||
- this.role == Role.PRODUCT_MANAGER;
+ return this.role == Role.DESIGNER;
};
this.$scope.getStatus = ():string => {
@@ -612,13 +603,6 @@ export class WorkspaceViewModel {
if (!this.$scope.component.isLatestVersion() && Role.OPS != this.role && Role.GOVERNOR != this.role) {
result = false;
}
- if (this.role === Role.PRODUCT_MANAGER && !this.$scope.component.isProduct()) {
- result = false;
- }
- if ((this.role === Role.DESIGNER || this.role === Role.TESTER)
- && this.$scope.component.isProduct()) {
- result = false;
- }
if (ComponentState.NOT_CERTIFIED_CHECKOUT === this.$scope.component.lifecycleState && this.$scope.isViewMode()) {
result = false;
}
@@ -639,10 +623,16 @@ export class WorkspaceViewModel {
this.$scope.$watch('$state.current.name', (newVal:string):void => {
if (newVal) {
this.$scope.isComposition = (newVal.indexOf(States.WORKSPACE_COMPOSITION) > -1);
- this.$scope.isDeployment = (newVal.indexOf(States.WORKSPACE_DEPLOYMENT) > -1);
+ this.$scope.isDeployment = newVal == States.WORKSPACE_DEPLOYMENT;
}
});
+ this.$scope.getTabTitle = ():string => {
+ return this.$scope.leftBarTabs.menuItems.find((menuItem:MenuItem)=>{
+ return menuItem.state == this.$scope.$state.current.name;
+ }).text;
+ };
+
this.$scope.reload = (component:Component):void => {
this.$state.go(this.$state.current.name,{id:component.uniqueId},{reload:true});
};
@@ -658,7 +648,11 @@ export class WorkspaceViewModel {
private initVersionObject = ():void => {
this.$scope.versionsList = (this.$scope.component.getAllVersionsAsSortedArray()).reverse();
- this.$scope.changeVersion = {selectedVersion: _.find(this.$scope.versionsList, {versionId: this.$scope.component.uniqueId})};
+ this.$scope.changeVersion = {
+ selectedVersion: _.find(this.$scope.versionsList, (versionObj)=> {
+ return versionObj.versionId === this.$scope.component.uniqueId;
+ })
+ };
};
private getNewComponentBreadcrumbItem = ():MenuItem => {
diff --git a/catalog-ui/src/app/view-models/workspace/workspace-view.html b/catalog-ui/src/app/view-models/workspace/workspace-view.html
index dbb7fa6d63..19ebefe7a5 100644
--- a/catalog-ui/src/app/view-models/workspace/workspace-view.html
+++ b/catalog-ui/src/app/view-models/workspace/workspace-view.html
@@ -3,8 +3,11 @@
<div class="w-sdc-main-container">
<div class="w-sdc-left-sidebar" data-ng-if="!isComposition">
- <div class="i-sdc-left-sidebar-item">
- <expand-collapse-menu-box menu-items-group="leftBarTabs" menu-title="{{menuComponentTitle}}" parent-scope="this"> </expand-collapse-menu-box>
+ <div class="menu-header" tooltips tooltip-content="{{menuComponentTitle}}">
+ {{menuComponentTitle}}
+ </div>
+ <div class="i-sdc-designer-sidebar-section-content-item" ng-class="{'selected': menuItem.state == $state.current.name}" ng-repeat="menuItem in leftBarTabs.menuItems track by $index">
+ <div class="expand-collapse-menu-box-item-text" ng-click="onMenuItemPressed(menuItem.state)" ng-class="{'disabled': menuItem.isDisabled }" data-tests-id="{{menuItem.text}}">{{menuItem.text}}</div>
</div>
</div>
@@ -54,22 +57,22 @@
<button ng-if="!isViewMode() && isCreateMode()" data-ng-disabled="!isValidForm || isDisableMode() || isLoading" ng-click="save()" class="tlv-btn outline green" data-tests-id="create/save">Create</button>
- <span data-ng-if="(isDesigner() || isProductManager()) && !isCreateMode() && component.lifecycleState === 'NOT_CERTIFIED_CHECKOUT'" sdc-smart-tooltip=""
+ <span data-ng-if="isDesigner() && !isCreateMode() && component.lifecycleState === 'NOT_CERTIFIED_CHECKOUT'" sdc-smart-tooltip=""
data-ng-class="{'disabled' : !isValidForm || isDisableMode() || isViewMode()}" ng-click="changeLifecycleState('deleteVersion')"
class="sprite-new delete-btn" data-tests-id="delete_version" sdc-smart-tooltip="">Delete</span>
<span data-ng-if="isDesigner()" data-ng-class="{'disabled' :isDisableMode() || isViewMode()}" ng-click="revert()" class="sprite-new revert-btn" data-tests-id="revert"
data-ng-show="showFullIcons()" sdc-smart-tooltip="">Revert</span>
- <span data-ng-if="isComposition && !component.isProduct()" class="sprite-new print-screen-btn" entity="component" print-graph-screen data-tests-id="printScreen"></span>
+ <span data-ng-if="isComposition" class="sprite-new print-screen-btn" entity="component" print-graph-screen data-tests-id="printScreen"></span>
<span class="delimiter"></span>
<span class="sprite-new x-btn" data-ng-click="goToBreadcrumbHome()" sdc-smart-tooltip="">Close</span>
</div>
</div>
-
- <div data-ng-if="component.creationDate && (!isComposition && !isDeployment)" class="sdc-asset-creation-info"><b>Created:</b>&nbsp;{{component.creationDate | date:'MM/dd/yyyy'}},&nbsp;{{component.creatorFullName}}&nbsp;|&nbsp;<b>Modifed:</b>&nbsp;{{component.lastUpdateDate | date:'MM/dd/yyyy'}}&nbsp;|&nbsp;<b>UUID:</b>&nbsp;{{component.uuid}}<b>&nbsp;Invariant UUID:</b>&nbsp;{{component.invariantUUID}}</div>
-
+ <div class="tab-title" data-ng-if="!isComposition && !isDeployment">
+ {{getTabTitle()}}
+ </div>
<div class="w-sdc-main-container-body-content" data-ng-class="{'third-party':thirdParty}" data-ui-view></div>
</div>
</div>
diff --git a/catalog-ui/src/app/view-models/workspace/workspace.less b/catalog-ui/src/app/view-models/workspace/workspace.less
index 278708ca33..b7331b5f93 100644
--- a/catalog-ui/src/app/view-models/workspace/workspace.less
+++ b/catalog-ui/src/app/view-models/workspace/workspace.less
@@ -27,10 +27,46 @@
}
.w-sdc-left-sidebar {
- padding: 3px 3px 0px 0px;
- background-color: @main_color_p;
- box-shadow: 7px -3px 6px -8px @main_color_n;
+ padding: 0px;
+ background-color: @tlv_color_t;
+ box-shadow: none;
z-index: 2;
+ border-right: 1px solid @main_color_o;
+ .menu-header{
+ border-bottom: 1px solid @main_color_o;
+ height: 53px;
+ .f-type._16_m;
+ font-weight: 700;
+ line-height: 53px;
+ padding-left: 40px;
+ padding-right: 10px;
+ width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ display: inline-block;
+ white-space: nowrap;
+ }
+ .i-sdc-designer-sidebar-section-content-item{
+ .f-type._13_m;
+ color: @main_color_m;
+ margin-left: 20px;
+ padding-left: 20px;
+ margin-top: 20px;
+ height: 17px;
+ .hand;
+ &:hover{
+ color: @func_color_s;
+ font-weight: 600;
+ }
+ &.selected{
+ border-left: 4px solid @main_color_a;
+ color: @main_color_a;
+ margin-left: 18px;
+ padding-left: 18px;
+ font-weight: 600;
+
+ }
+ }
}
.sdc-asset-creation-info {
@@ -128,17 +164,21 @@
margin-top: 6px;
}
}
+ .tab-title{
+ height: 110px;
+ padding-left: 100px;
+ line-height: 110px;
+ .f-type ._28;
+ }
.w-sdc-main-container-body-content {
- height:calc(~'100% - @{action_nav_height}');
-
- text-align: center;
+ height:calc(~'100% - @{action_nav_height} - @{tab_title}');
align-items: center;
- padding: 40px 14% 20px 14%;
+ padding: 0 100px 20px 100px;
&.third-party {
text-align: left;
padding: 0;
position: absolute;
- top: @action_nav_height;
+ top: @action_nav_height + @tab_title;
left: 0;
right: 0;
bottom: 0;
@@ -147,7 +187,3 @@
}
}
-
-.properties-assignment .sdc-workspace-container .w-sdc-main-right-container .w-sdc-main-container-body-content{
- padding: 80px 2% 40px 2%;
-}
diff --git a/catalog-ui/src/assets/languages/en_US.json b/catalog-ui/src/assets/languages/en_US.json
index 2957f8ac4a..85acea6d02 100644
--- a/catalog-ui/src/assets/languages/en_US.json
+++ b/catalog-ui/src/assets/languages/en_US.json
@@ -200,10 +200,8 @@
"=========== NEW RESOURCE SERVICE ===========": "",
"NEW_SERVICE_RESOURCE_WRAPPER_TAB_GENERAL_INFORMATION": "General Information",
- "NEW_SERVICE_RESOURCE_WRAPPER_TAB_ASSIGN_PRODUCT_HIERARCHY": "Assign Product Hierarchy",
"NEW_SERVICE_RESOURCE_WRAPPER_TAB_ADDITIONAL_INFO": "Additional Information",
"NEW_SERVICE_RESOURCE_WRAPPER_TAB_BILLING_AND_ORDERING": "Order Attributes & Rules",
- "NEW_SERVICE_RESOURCE_WRAPPER_TAB_PRODUCT_COMPOSITION": "Bill Attributes & Rules",
"NEW_SERVICE_RESOURCE_SAVE_BUTTON": "Save",
"NEW_SERVICE_RESOURCE_DONE_BUTTON": "Done",
@@ -226,9 +224,7 @@
"NEW_SERVICE_RESOURCE_ERROR_SERVICE_ICON": "Icon required.",
"NEW_SERVICE_RESOURCE_ERROR_RESOURCE_ICON": "Icon required.",
"NEW_SERVICE_RESOURCE_ERROR_RESOURCE_NAME_REQUIRED": "Name is required.",
- "NEW_SERVICE_RESOURCE_ERROR_PRODUCT_NAME_REQUIRED": "Name is required.",
"NEW_SERVICE_RESOURCE_ERROR_RESOURCE_DESCRIPTION_REQUIRED": "Description is required.",
- "NEW_SERVICE_RESOURCE_ERROR_PRODUCT_DESCRIPTION_REQUIRED": "Description is required.",
"NEW_SERVICE_RESOURCE_ERROR_VENDOR_NAME_REQUIRED": "Vendor name is required.",
"NEW_SERVICE_RESOURCE_ERROR_VENDOR_RELEASE_REQUIRED": "Vendor Release is required.",
"NEW_SERVICE_RESOURCE_ERROR_TEMPLATE_REQUIRED": "Template is required.",
@@ -238,7 +234,6 @@
"NEW_SERVICE_RESOURCE_ERROR_TOSCA_FILE_REQUIRED": "Tosca file is required.",
"NEW_SERVICE_RESOURCE_ERROR_VALID_CSAR_EXTENSIONS_TITLE": "Invalid csar file",
"NEW_SERVICE_RESOURCE_ERROR_VALID_CSAR_EXTENSIONS": "File extension should be {{extensions}}.",
- "NEW_PRODUCT_NO_CATEGORIES_TO_DISPLAY": "Your product is not assigned to any group yet. <br> To select/find a group, begin typing above and select group to add",
"=========== SUGGESTED ICONS TOOLTIP ===========": "",
"call_controll": "Call Control",
diff --git a/catalog-ui/src/assets/styles/app.less b/catalog-ui/src/assets/styles/app.less
index 1ce1801d9b..13d88a388e 100644
--- a/catalog-ui/src/assets/styles/app.less
+++ b/catalog-ui/src/assets/styles/app.less
@@ -11,7 +11,6 @@
@import 'sprite-old.less';
@import 'sprite.less';
-@import 'sprite-product-icons.less';
@import 'sprite-resource-icons.less';
@import 'sprite-services-icons.less';
@@ -90,6 +89,7 @@
@import '../../app/view-models/modals/message-modal/message-client-modal/client-message-modal.less';
@import '../../app/view-models/modals/message-modal/message-server-modal/server-message-modal.less';
@import '../../app/view-models/modals/onboarding-modal/onboarding-modal.less';
+@import '../../app/view-models/modals/icons-modal/icons-modal-view.less';
@import '../../app/view-models/onboard-vendor/onboard-vendor.less';
@import '../../app/view-models/support/support.less';
@import '../../app/view-models/tabs/general-tab.less';
@@ -107,12 +107,10 @@
@import '../../app/view-models/workspace/tabs/distribution/disribution-status-modal/disribution-status-modal.less';
@import '../../app/view-models/workspace/tabs/distribution/distribution.less';
@import '../../app/view-models/workspace/tabs/general/general.less';
-@import '../../app/view-models/workspace/tabs/icons/icons.less';
@import '../../app/view-models/workspace/tabs/information-artifacts/information-artifacts.less';
@import '../../app/view-models/workspace/tabs/inputs/inputs.less';
@import '../../app/view-models/workspace/tabs/inputs/resource-input/resource-inputs.less';
@import '../../app/view-models/workspace/tabs/inputs/service-input/service-inputs.less';
-@import '../../app/view-models/workspace/tabs/product-hierarchy/product-hierarchy.less';
@import '../../app/view-models/workspace/tabs/properties/properties.less';
@import '../../app/view-models/workspace/tabs/req-and-capabilities/req-and-capabilities.less';
@import '../../app/view-models/workspace/tabs/tosca-artifacts/tosca-artifacts.less';
diff --git a/catalog-ui/src/assets/styles/images/resource-icons/vnfconfiguration.png b/catalog-ui/src/assets/styles/images/resource-icons/vnfconfiguration.png
new file mode 100644
index 0000000000..66c64c3fe6
--- /dev/null
+++ b/catalog-ui/src/assets/styles/images/resource-icons/vnfconfiguration.png
Binary files differ
diff --git a/catalog-ui/src/assets/styles/images/sprites/sprite-global.png b/catalog-ui/src/assets/styles/images/sprites/sprite-global.png
index 7a795c7a91..962478fed3 100644
--- a/catalog-ui/src/assets/styles/images/sprites/sprite-global.png
+++ b/catalog-ui/src/assets/styles/images/sprites/sprite-global.png
Binary files differ
diff --git a/catalog-ui/src/assets/styles/images/sprites/sprite-product-icons.png b/catalog-ui/src/assets/styles/images/sprites/sprite-product-icons.png
deleted file mode 100644
index e85467a09c..0000000000
--- a/catalog-ui/src/assets/styles/images/sprites/sprite-product-icons.png
+++ /dev/null
Binary files differ
diff --git a/catalog-ui/src/assets/styles/images/sprites/sprite-resource-icons.png b/catalog-ui/src/assets/styles/images/sprites/sprite-resource-icons.png
index 7d520a8628..27e96f3ba2 100644
--- a/catalog-ui/src/assets/styles/images/sprites/sprite-resource-icons.png
+++ b/catalog-ui/src/assets/styles/images/sprites/sprite-resource-icons.png
Binary files differ
diff --git a/catalog-ui/src/assets/styles/mixins.less b/catalog-ui/src/assets/styles/mixins.less
index 4a0356d810..fbc5f83df1 100644
--- a/catalog-ui/src/assets/styles/mixins.less
+++ b/catalog-ui/src/assets/styles/mixins.less
@@ -34,6 +34,10 @@
font-family: @font-opensans-light;
font-size: 36px;
}
+ ._28 {
+ font-family: @font-opensans-light;
+ font-size: 28px;
+ }
._24 {
font-family: @font-opensans-light;
font-size: 24px;
diff --git a/catalog-ui/src/assets/styles/modal.less b/catalog-ui/src/assets/styles/modal.less
index eb9de92f80..3307bfc56a 100644
--- a/catalog-ui/src/assets/styles/modal.less
+++ b/catalog-ui/src/assets/styles/modal.less
@@ -33,6 +33,10 @@ MODAL SIZES
width: 552px;
}
+.modal-dialog.modal-sdc-auto {
+ width: auto;
+}
+
.modal-dialog.modal-sdc-xsm {
width: 432px;
}
@@ -324,7 +328,8 @@ NEW DESIGN MODAL
.modal-sdc-l,
.modal-sdc-md,
.modal-sdc-sm,
-.modal-sdc-xsm {
+.modal-sdc-xsm,
+.modal-sdc-auto {
.w-sdc-classic-top-line-modal {
padding: 0 30px;
diff --git a/catalog-ui/src/assets/styles/sprite-product-icons.less b/catalog-ui/src/assets/styles/sprite-product-icons.less
deleted file mode 100644
index 3485ec89a3..0000000000
--- a/catalog-ui/src/assets/styles/sprite-product-icons.less
+++ /dev/null
@@ -1,71 +0,0 @@
-.sprite-product-icons {
- background-image: url('images/sprites/sprite-product-icons.png');
- display: inline-block;
-}
-
-.sprite-product-icons.disable { opacity:0.5;}
-
-.sprite-product-icons.setting { background-position: -291px -102px; width: 61px; height: 67px;}
-.sprite-product-icons.setting.small { background-position: -217px -142px; width: 29px; height: 28px;}
-.sprite-product-icons.setting.medium { background-position: -148px -130px; width: 41px; height: 40px;}
-.sprite-product-icons.setting.large { background-position: -77px -110px; width: 60px; height: 60px;}
-
-.sprite-product-icons.cloud { background-position: -290px -215px; width: 64px; height: 43px;}
-.sprite-product-icons.cloud.small { background-position: -217px -232px; width: 29px; height: 28px;}
-.sprite-product-icons.cloud.medium { background-position: -148px -220px; width: 41px; height: 40px;}
-.sprite-product-icons.cloud.large { background-position: -77px -200px; width: 60px; height: 60px;}
-
-.sprite-product-icons.security { background-position: -289px -293px; width: 50px; height: 57px;}
-.sprite-product-icons.security.small { background-position: -217px -321px; width: 29px; height: 28px;}
-.sprite-product-icons.security.medium { background-position: -148px -310px; width: 41px; height: 40px;}
-.sprite-product-icons.security.large { background-position: -77px -290px; width: 60px; height: 60px;}
-
-.sprite-product-icons.network { background-position: -290px -383px; width: 56px; height: 57px;}
-.sprite-product-icons.network.small { background-position: -217px -411px; width: 29px; height: 29px;}
-.sprite-product-icons.network.medium { background-position: -148px -399px; width: 41px; height: 41px;}
-.sprite-product-icons.network.large { background-position: -77px -380px; width: 60px; height: 60px;}
-
-.sprite-product-icons.orphan { background-position: -290px -478px; width: 52px; height: 52px;}
-.sprite-product-icons.orphan.small { background-position: -217px -500px; width: 29px; height: 29px;}
-.sprite-product-icons.orphan.medium { background-position: -148px -488px; width: 41px; height: 41px;}
-.sprite-product-icons.orphan.large { background-position: -77px -470px; width: 60px; height: 60px;}
-
-.sprite-product-icons.defaulticon { background-position: -290px -478px; width: 52px; height: 52px;}
-.sprite-product-icons.defaulticon.small { background-position: -217px -500px; width: 29px; height: 29px;}
-.sprite-product-icons.defaulticon.medium { background-position: -148px -488px; width: 41px; height: 41px;}
-.sprite-product-icons.defaulticon.large { background-position: -77px -470px; width: 60px; height: 60px;}
-
-.sprite-product-icons.vfw { background-position: -289px -548px; width: 73px; height: 73px;}
-.sprite-product-icons.vfw.small { background-position: -217px -591px; width: 29px; height: 29px;}
-.sprite-product-icons.vfw.medium { background-position: -148px -580px; width: 41px; height: 41px;}
-.sprite-product-icons.vfw.large { background-position: -77px -560px; width: 60px; height: 61px;}
-
-.sprite-product-icons.wanx { background-position: -290px -664px; width: 59px; height: 47px;}
-.sprite-product-icons.wanx.small { background-position: -217px -681px; width: 30px; height: 30px;}
-.sprite-product-icons.wanx.medium { background-position: -148px -670px; width: 41px; height: 41px;}
-.sprite-product-icons.wanx.large { background-position: -77px -651px; width: 60px; height: 60px;}
-
-.sprite-product-icons.vrouter { background-position: -289px -758px; width: 69px; height: 43px;}
-.sprite-product-icons.vrouter.small { background-position: -217px -772px; width: 29px; height: 29px;}
-.sprite-product-icons.vrouter.medium { background-position: -148px -760px; width: 41px; height: 41px;}
-.sprite-product-icons.vrouter.large { background-position: -77px -741px; width: 60px; height: 60px;}
-
-.sprite-product-icons.ucpe { background-position: -289px -832px; width: 59px; height: 60px;}
-.sprite-product-icons.ucpe.small { background-position: -217px -862px; width: 28px; height: 29px;}
-.sprite-product-icons.ucpe.medium { background-position: -148px -849px; width: 41px; height: 41px;}
-.sprite-product-icons.ucpe.large { background-position: -77px -831px; width: 60px; height: 61px;}
-
-.sprite-product-icons.mobility { background-position: -288px -919px; width: 64px; height: 62px;}
-.sprite-product-icons.mobility.small { background-position: -216px -952px; width: 29px; height: 29px;}
-.sprite-product-icons.mobility.medium { background-position: -147px -940px; width: 41px; height: 41px;}
-.sprite-product-icons.mobility.large { background-position: -76px -921px; width: 60px; height: 60px;}
-
-.sprite-product-icons.wanx_customer_managed { background-position: -290px -1024px; width: 58px; height: 62px;}
-.sprite-product-icons.wanx.small_customer_managed { background-position: -217px -1041px; width: 30px; height: 38px;}
-.sprite-product-icons.wanx.medium_customer_managed { background-position: -148px -1030px; width: 42px; height: 47px;}
-.sprite-product-icons.wanx.large_customer_managed { background-position: -77px -1011px; width: 61px; height: 66px;}
-
-.sprite-product-icons.wanx_attr_managed { background-position: -290px -1114px; width: 59px; height: 62px;}
-.sprite-product-icons.wanx.small_att_managed { background-position: -218px -1131px; width: 31px; height: 36px;}
-.sprite-product-icons.wanx.medium_att_managed { background-position: -149px -1120px; width: 42px; height: 47px;}
-.sprite-product-icons.wanx.large_att_managed { background-position: -77px -1101px; width: 60px; height: 67px;}
diff --git a/catalog-ui/src/assets/styles/sprite-resource-icons.less b/catalog-ui/src/assets/styles/sprite-resource-icons.less
index 153e8c042c..2c19ee3291 100644
--- a/catalog-ui/src/assets/styles/sprite-resource-icons.less
+++ b/catalog-ui/src/assets/styles/sprite-resource-icons.less
@@ -266,3 +266,4 @@
.sprite-resource-icons.allotted_resource.medium { background-position: -141px -4898px; width: 41px; height: 41px;}
.sprite-resource-icons.allotted_resource.large { background-position: -70px -4879px; width: 60px; height: 60px;}
+.sprite-resource-icons.vnfconfiguration.large { background-position: -70px -4959px; width: 60px; height: 60px;}
diff --git a/catalog-ui/src/assets/styles/sprite.less b/catalog-ui/src/assets/styles/sprite.less
index 0c0f538388..2076744854 100644
--- a/catalog-ui/src/assets/styles/sprite.less
+++ b/catalog-ui/src/assets/styles/sprite.less
@@ -238,6 +238,8 @@
.round-expand-icon:hover { background-position: -100px -1188px; width: 15px; height: 15px; }
.round-expand-icon.open { background-position: -50px -1216px; width: 15px; height: 15px; }
.round-expand-icon.open:hover { background-position: -100px -1216px; width: 15px; height: 15px; }
+.update-component-icon { background-position: -140px -1183px; width: 20px; height: 20px;}
+.update-component-icon:hover { background-position: -170px -1183px; width: 20px; height: 20px;}
/*
.sprite-new.expand-asset-icon { background-position: -740px -590px; width: 40px; height: 40px; }
.sprite-new.view-info-icon { background-position: -739px -621px; width: 40px; height: 40px; }
diff --git a/catalog-ui/src/assets/styles/variables-old.less b/catalog-ui/src/assets/styles/variables-old.less
index 57f3fc24b8..d16252dab4 100644
--- a/catalog-ui/src/assets/styles/variables-old.less
+++ b/catalog-ui/src/assets/styles/variables-old.less
@@ -2,7 +2,7 @@
@images: "images";
/* Colors */
-@color_a: #3b7b9b; // product category
+@color_a: #3b7b9b;
@color_b: #666666;
@color_c: #ffffff;
@color_d: #1d9a95; // dashboard service (S at the top left of the card)
diff --git a/catalog-ui/src/assets/styles/variables.less b/catalog-ui/src/assets/styles/variables.less
index 3c23bdbe5e..163737466e 100644
--- a/catalog-ui/src/assets/styles/variables.less
+++ b/catalog-ui/src/assets/styles/variables.less
@@ -47,5 +47,6 @@
@top_nav_height: 50px;
@top_nav_admin_height: 44px;
@action_nav_height: 53px;
+@tab_title: 110px;
@footer_height: 89px;
@border_color_view-mode: #ededed;
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java
index 7d37de7965..c962500c2b 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/Configuration.java
@@ -82,6 +82,7 @@ public class Configuration extends BasicConfiguration {
private List<String> resourceTypes;
private List<String> excludeResourceCategory;
+ private List<String> excludeResourceType;
private Map<String, Object> deploymentResourceArtifacts;
private Map<String, Object> deploymentResourceInstanceArtifacts;
private Map<String, Object> toscaArtifacts;
@@ -361,6 +362,15 @@ public class Configuration extends BasicConfiguration {
public void setExcludeResourceCategory(List<String> excludeResourceCategory) {
this.excludeResourceCategory = excludeResourceCategory;
}
+
+ public List<String> getExcludeResourceType() {
+ return excludeResourceType;
+ }
+
+ public void setExcludeResourceType(List<String> excludeResourceType) {
+ this.excludeResourceType = excludeResourceType;
+ }
+
public Map<String, Object> getToscaArtifacts() {
return toscaArtifacts;
@@ -842,6 +852,7 @@ public class Configuration extends BasicConfiguration {
String host;
Integer port;
String downloadCsarUri;
+ String healthCheckUri;
public String getProtocol() {
return protocol;
@@ -875,6 +886,14 @@ public class Configuration extends BasicConfiguration {
this.downloadCsarUri = downloadCsarUri;
}
+ public String getHealthCheckUri() {
+ return healthCheckUri;
+ }
+
+ public void setHealthCheckUri(String healthCheckUri) {
+ this.healthCheckUri = healthCheckUri;
+ }
+
@Override
public String toString() {
return "OnboardingConfig [protocol=" + protocol + ", host=" + host + ", port=" + port + ", downloadCsarUri="
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java
index 04640e7fc7..fcde7f13ac 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/Constants.java
@@ -125,5 +125,6 @@ public interface Constants {
public static final String VF_LICENSE_DESCRIPTION = "VF license file";
public static final String GET_INPUT = "get_input";
public static final String SERVICE_TEMPLATE_FILE_POSTFIX = "ServiceTemplate.yaml";
+ public static final String SERVICE_TEMPLATES_CONTAINING_FOLDER = "Definitions/";
public static final String UNBOUNDED = "unbounded";
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java
index 653b8b0866..2e4f54f153 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/api/HealthCheckInfo.java
@@ -20,12 +20,19 @@
package org.openecomp.sdc.common.api;
+import java.lang.reflect.Type;
+import java.util.List;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+
public class HealthCheckInfo {
private HealthCheckComponent healthCheckComponent;
private HealthCheckStatus healthCheckStatus;
private String version;
private String description;
+ private List<HealthCheckInfo> componentsInfo;
public HealthCheckInfo(HealthCheckComponent healthCheckComponent, HealthCheckStatus healthCheckStatus,
String version, String description) {
@@ -36,6 +43,16 @@ public class HealthCheckInfo {
this.description = description;
}
+ public HealthCheckInfo(HealthCheckComponent healthCheckComponent, HealthCheckStatus healthCheckStatus,
+ String version, String description, List<HealthCheckInfo> componentsInfo) {
+ super();
+ this.healthCheckComponent = healthCheckComponent;
+ this.healthCheckStatus = healthCheckStatus;
+ this.version = version;
+ this.description = description;
+ this.componentsInfo = componentsInfo;
+ }
+
public HealthCheckInfo() {
super();
}
@@ -48,6 +65,14 @@ public class HealthCheckInfo {
return healthCheckStatus;
}
+ public List<HealthCheckInfo> getComponentsInfo() {
+ return componentsInfo;
+ }
+
+ public void setComponentsInfo(List<HealthCheckInfo> componentsInfo) {
+ this.componentsInfo = componentsInfo;
+ }
+
public String getVersion() {
return version;
}
@@ -61,7 +86,8 @@ public class HealthCheckInfo {
}
public enum HealthCheckComponent {
- FE, BE, TITAN, ES, DE;
+ FE, BE, TITAN, DE, ON_BOARDING, CASSANDRA,
+ CAS, ZU;//Amdocs components
}
public enum HealthCheckStatus {
@@ -71,6 +97,14 @@ public class HealthCheckInfo {
@Override
public String toString() {
return "HealthCheckInfo [healthCheckComponent=" + healthCheckComponent + ", healthCheckStatus="
- + healthCheckStatus + ", version=" + version + ", description=" + description + "]";
+ + healthCheckStatus + ", version=" + version + ", description=" + description + ", componentsInfo="
+ + componentsInfo + "]";
+ }
+
+ public static void main(String[] args) {
+ String des = "[{healthCheckComponent=BE4, healthCheckStatus=UP, version=0.0.1-SNAPSHOT, description=OK}, {healthCheckComponent=BE, healthCheckStatus=UP, version=1710.0.0-SNAPSHOT, description=OK}, {healthCheckComponent=BE5, healthCheckStatus=UP, version=2.1.9, description=OK}]";
+ Type listType = new TypeToken<List<HealthCheckInfo>>(){}.getType();
+ List<HealthCheckInfo> componentsInfo = new Gson().fromJson(des.toString(), listType);
+ System.out.println(componentsInfo.toString());
}
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java
index 0f45d34886..aaee26004f 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/config/EcompErrorCode.java
@@ -26,7 +26,7 @@ public enum EcompErrorCode {
"An Authentication failure occured during access to UEB server. Please check that UEB keys are configured correctly in ASDC BE distribution configuration."), E_199(
"Internal authentication problem. Description: %s"),
- E_200("ASDC Backend probably lost connectivity to either one of the following components: Titan DB, Elasticsearch, UEB Cluster. Please check the logs for more information."), E_201(
+ E_200("ASDC Backend probably lost connectivity to either one of the following components: Titan DB, Cassandra, Onboarding, UEB Cluster. Please check the logs for more information."), E_201(
"ASDC Backend probably lost connectivity to Titan DB. Please check the logs for more information."), E_202(
"ASDC Backend probably lost connectivity to ElasticSearch. Please check the logs for more information."), E_203(
"ASDC Backend probably lost connectivity to UEB Cluster. Please check the logs for more information.",
@@ -34,7 +34,7 @@ public enum EcompErrorCode {
"Unable to connect to a valid ASDC Backend Server",
"Please check connectivity from this FE instance towards BE or BE Load Balancer. Please check that parameters in FE configuration.yaml: beHost, beHttpPort and beSslPort point to a valid host and port values."),
- E_205("ASDC Backend Recovery to either one of the following components: Titan DB, Elasticsearch, UEB Cluster."), E_206(
+ E_205("ASDC Backend Recovery to either one of the following components: Titan DB, Cassandra, Onboarding, UEB Cluster."), E_206(
"ASDC Backend connection recovery to Titan DB."), E_207(
"ASDC Backend connection recovery to ElasticSearch."), E_208(
"ASDC Backend connection recovery to UEB Cluster."), E_209(
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java
index c89eeaf535..0b55fd1845 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java
@@ -153,4 +153,14 @@ public class GeneralUtility {
byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes());
return new String(encodeBase64);
}
+
+
+ /**
+ *
+ * @param String
+ * @return String is null or Empty
+ */
+ public static boolean isEmptyString(String str) {
+ return str == null || str.trim().isEmpty();
+ }
}
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java
index 3ea780a7f9..6c47659dad 100644
--- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java
+++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java
@@ -66,14 +66,18 @@ public class ValidationUtils {
public final static Pattern ENGLISH_PATTERN = Pattern.compile("^[\\p{Graph}\\x20]+$");
public final static Integer COMPONENT_DESCRIPTION_MAX_LENGTH = 1024;
+ public final static Integer SERVICE_TYPE_MAX_LENGTH = 400;
+ public final static Integer SERVICE_ROLE_MAX_LENGTH = 400;
+
public final static Integer TAG_MAX_LENGTH = 1024;
public final static Integer TAG_LIST_MAX_LENGTH = 1024;
- public final static Integer VENDOR_NAME_MAX_LENGTH = 25;
+ public final static Integer VENDOR_NAME_MAX_LENGTH = 60;
public final static Pattern VENDOR_NAME_PATTERN = Pattern
.compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$");
public final static Integer VENDOR_RELEASE_MAX_LENGTH = 25;
public final static Pattern VENDOR_RELEASE_PATTERN = Pattern
.compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$");
+ public final static Integer RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH = 65;
public final static Pattern CLEAN_FILENAME_PATTERN = Pattern.compile("[\\x00-\\x1f\\x80-\\x9f\\x5c/<?>\\*:|\"/]+");
@@ -318,14 +322,18 @@ public class ValidationUtils {
return true;
}
- public static boolean validateVendorName(String ventorName) {
- return VENDOR_NAME_PATTERN.matcher(ventorName).matches();
+ public static boolean validateVendorName(String vendorName) {
+ return VENDOR_NAME_PATTERN.matcher(vendorName).matches();
}
- public static boolean validateVendorNameLength(String ventorName) {
- return ventorName.length() <= VENDOR_NAME_MAX_LENGTH;
+ public static boolean validateVendorNameLength(String vendorName) {
+ return vendorName.length() <= VENDOR_NAME_MAX_LENGTH;
}
+ public static boolean validateResourceVendorModelNumberLength(String resourceVendorModelNumber) {
+ return resourceVendorModelNumber.length() <= RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH;
+ }
+
public static boolean validateVendorRelease(String vendorRelease) {
return VENDOR_RELEASE_PATTERN.matcher(vendorRelease).matches();
}
@@ -333,6 +341,16 @@ public class ValidationUtils {
public static boolean validateVendorReleaseLength(String vendorRelease) {
return vendorRelease.length() <= VENDOR_RELEASE_MAX_LENGTH;
}
+
+ public static boolean validateServiceTypeLength(String serviceType) {
+ return serviceType.length() <= SERVICE_TYPE_MAX_LENGTH;
+ }
+
+ public static boolean validateServiceRoleLength(String serviceRole) {
+ return serviceRole.length() <= SERVICE_ROLE_MAX_LENGTH;
+ }
+
+
public static boolean hasBeenCertified(String version) {
return NumberUtils.toDouble(version) >= 1;
@@ -509,5 +527,5 @@ public class ValidationUtils {
String stripped = HtmlCleaner.stripHtml(htmlText, false);
return stripped;
}
-
+
}
diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java
index 50c2b79d63..ae882d8a92 100644
--- a/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java
+++ b/common-app-api/src/test/java/org/openecomp/sdc/common/test/CommonUtilsTest.java
@@ -257,7 +257,7 @@ public class CommonUtilsTest {
@Test
public void validateVendorNameLengthTest() {
assertTrue(ValidationUtils.validateVendorNameLength("fsdlfsdlk.sdsd;"));
- assertFalse(ValidationUtils.validateVendorNameLength("ddddddddddddddddddddddsdfs"));
+ assertFalse(ValidationUtils.validateVendorNameLength("ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddsdfs"));
}
@Test
@@ -271,8 +271,8 @@ public class CommonUtilsTest {
@Test
public void validateVendorReleaseLengthTest() {
- assertTrue(ValidationUtils.validateVendorNameLength("fsdlfsdlk.sdsd;"));
- assertFalse(ValidationUtils.validateVendorNameLength("ddddddddddddddddddddddsdfs"));
+ assertTrue(ValidationUtils.validateVendorReleaseLength("fsdlfsdlk.sdsd;"));
+ assertFalse(ValidationUtils.validateVendorReleaseLength("ddddddddddddddddddddddsdfs"));
}
@Test
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ComponentMetadataDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ComponentMetadataDataDefinition.java
index 24d801262c..5fecac429a 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ComponentMetadataDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ComponentMetadataDataDefinition.java
@@ -28,6 +28,8 @@ import java.util.Map;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public abstract class ComponentMetadataDataDefinition extends ToscaDataDefinition implements Serializable {
@@ -35,7 +37,8 @@ public abstract class ComponentMetadataDataDefinition extends ToscaDataDefinitio
*
*/
private static final long serialVersionUID = -9114770126086263552L;
-
+ private static final Logger log = LoggerFactory.getLogger(ComponentMetadataDataDefinition.class.getName());
+
private String uniqueId;
private String name; // archiveName
@@ -156,13 +159,13 @@ public abstract class ComponentMetadataDataDefinition extends ToscaDataDefinitio
this.lastUpdateDate = other.getLastUpdateDate();
this.description = other.getDescription();
this.state = other.getState();
- this.tags = new ArrayList<String>(other.getTags());
+ this.tags = new ArrayList<>(other.getTags());
this.icon = other.getIcon();
this.contactId = other.getContactId();
this.UUID = other.getUUID();
this.normalizedName = other.getNormalizedName();
this.systemName = other.getSystemName();
- this.allVersions = new HashMap<String, String>(other.getAllVersions());
+ this.allVersions = new HashMap<>(other.getAllVersions());
this.isDeleted = other.isDeleted();
this.projectCode = other.getProjectCode();
this.csarUUID = other.getCsarUUID();
@@ -177,6 +180,8 @@ public abstract class ComponentMetadataDataDefinition extends ToscaDataDefinitio
}
public void setUniqueId(String uniqueId) {
+ if ( this.uniqueId != null && !this.uniqueId.equals( uniqueId ) )
+ log.warn("uniqueId changed more then once -> OLD : {} , NEW: {} ", this.uniqueId ,uniqueId );
this.uniqueId = uniqueId;
}
@@ -264,8 +269,10 @@ public abstract class ComponentMetadataDataDefinition extends ToscaDataDefinitio
return UUID;
}
- public void setUUID(String uUID) {
- UUID = uUID;
+ public void setUUID(String UUID) {
+ if ( this.UUID != null && !this.UUID.equals( UUID ) )
+ log.warn("UUID changed more then once -> OLD : {} , NEW: {} ", this.UUID, UUID );
+ this.UUID = UUID;
}
public String getNormalizedName() {
@@ -297,6 +304,8 @@ public abstract class ComponentMetadataDataDefinition extends ToscaDataDefinitio
}
public void setInvariantUUID(String invariantUUID) {
+ if ( this.invariantUUID != null && !this.invariantUUID.equals( invariantUUID ) )
+ log.warn("InvariantUUID changed more then once -> OLD : {} , NEW: {} ", this.invariantUUID ,invariantUUID );
this.invariantUUID = invariantUUID;
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java
index 7b112ce129..9675cd37fb 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ResourceMetadataDataDefinition.java
@@ -34,6 +34,7 @@ public class ResourceMetadataDataDefinition extends ComponentMetadataDataDefinit
private String vendorName;
private String vendorRelease;
+ private String resourceVendorModelNumber;
private ResourceTypeEnum resourceType = ResourceTypeEnum.VFC; // ResourceType.VFC
// is
// default
@@ -44,12 +45,14 @@ public class ResourceMetadataDataDefinition extends ComponentMetadataDataDefinit
public ResourceMetadataDataDefinition() {
super();
+ resourceVendorModelNumber = "";
}
public ResourceMetadataDataDefinition(ResourceMetadataDataDefinition other) {
super(other);
this.vendorName = other.getVendorName();
this.vendorRelease = other.getVendorRelease();
+ this.resourceVendorModelNumber = other.getResourceVendorModelNumber();
this.isAbstract = other.isHighestVersion();
this.resourceType = other.getResourceType();
this.toscaResourceName = other.getToscaResourceName();
@@ -70,6 +73,15 @@ public class ResourceMetadataDataDefinition extends ComponentMetadataDataDefinit
public void setVendorRelease(String vendorRelease) {
this.vendorRelease = vendorRelease;
}
+
+ public String getResourceVendorModelNumber() {
+ return resourceVendorModelNumber;
+ }
+
+ public void setResourceVendorModelNumber(String resourceVendorModelNumber) {
+ this.resourceVendorModelNumber = resourceVendorModelNumber;
+ }
+
public ResourceTypeEnum getResourceType() {
return resourceType;
@@ -114,7 +126,8 @@ public class ResourceMetadataDataDefinition extends ComponentMetadataDataDefinit
@Override
public String toString() {
return "ResourceMetadataDataDefinition [vendorName=" + vendorName + ", vendorRelease=" + vendorRelease
- + ", resourceType=" + resourceType + ", isAbstract=" + isAbstract + super.toString() + "]";
+ + ", resourceVendorModelNumber=" + resourceVendorModelNumber + ", resourceType=" + resourceType +
+ ", isAbstract=" + isAbstract + super.toString() + "]";
}
@Override
@@ -127,6 +140,7 @@ public class ResourceMetadataDataDefinition extends ComponentMetadataDataDefinit
result = prime * result + ((resourceType == null) ? 0 : resourceType.hashCode());
result = prime * result + ((vendorName == null) ? 0 : vendorName.hashCode());
result = prime * result + ((vendorRelease == null) ? 0 : vendorRelease.hashCode());
+ result = prime * result + ((resourceVendorModelNumber == null)? 0 : resourceVendorModelNumber.hashCode());
return result;
}
@@ -170,6 +184,11 @@ public class ResourceMetadataDataDefinition extends ComponentMetadataDataDefinit
return false;
} else if (!vendorRelease.equals(other.vendorRelease))
return false;
+ if (resourceVendorModelNumber == null) {
+ if (other.resourceVendorModelNumber != null)
+ return false;
+ } else if (!resourceVendorModelNumber.equals(other.resourceVendorModelNumber))
+ return false;
return super.equals(obj);
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java
index 4f3486e457..4a42436583 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/components/ServiceMetadataDataDefinition.java
@@ -33,6 +33,8 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti
public static final String EMPTY_STR = "";
private String distributionStatus;
+ private String serviceType;
+ private String serviceRole;
private Boolean ecompGeneratedNaming = true;
@@ -40,10 +42,14 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti
public ServiceMetadataDataDefinition() {
super();
+ serviceType = "";
+ serviceRole = "";
}
public ServiceMetadataDataDefinition(ServiceMetadataDataDefinition other) {
super(other);
+ serviceType = other.getServiceType();
+ serviceRole = other.getServiceRole();
}
public String getDistributionStatus() {
@@ -53,6 +59,22 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti
public void setDistributionStatus(String distributionStatus) {
this.distributionStatus = distributionStatus;
}
+
+ public String getServiceType(){
+ return serviceType;
+ }
+
+ public void setServiceType(String serviceType){
+ this.serviceType = serviceType;
+ }
+
+ public String getServiceRole(){
+ return serviceRole;
+ }
+
+ public void setServiceRole(String serviceRole){
+ this.serviceRole = serviceRole;
+ }
public Boolean isEcompGeneratedNaming() {
return ecompGeneratedNaming;
@@ -73,8 +95,8 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti
@Override
public String toString() {
return "ServiceMetadataDataDefinition [ distributionStatus=" + distributionStatus
- + ", ecompGeneratedNaming=" + ecompGeneratedNaming + ", namingPolicy=" + namingPolicy
- + ", parent=" + super.toString() + "]";
+ + ", serviceType=" + serviceType + ", serviceRole=" + serviceRole + ", ecompGeneratedNaming="
+ + ecompGeneratedNaming + ", namingPolicy=" + namingPolicy + ", parent=" + super.toString() + "]";
}
@Override
@@ -84,6 +106,8 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti
result = prime * result + ((distributionStatus == null) ? 0 : distributionStatus.hashCode());
result = prime * result + ((ecompGeneratedNaming == null) ? 0 : ecompGeneratedNaming.hashCode());
result = prime * result + ((namingPolicy == null) ? 0 : namingPolicy.hashCode());
+ result = prime * result + ((serviceType == null) ? 0 : serviceType.hashCode());
+ result = prime * result + ((serviceRole == null) ? 0 : serviceRole.hashCode());
return result;
}
@@ -117,6 +141,16 @@ public class ServiceMetadataDataDefinition extends ComponentMetadataDataDefiniti
return false;
} else if (!namingPolicy.equals(other.namingPolicy))
return false;
+ if (serviceType == null){
+ if (other.serviceType != null)
+ return false;
+ } else if (!serviceType.equals(other.serviceType))
+ return false;
+ if (serviceRole == null){
+ if (other.serviceRole != null)
+ return false;
+ } else if (!serviceRole.equals(other.serviceRole))
+ return false;
return super.equals(obj);
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListDataDefinition.java
index 424b15059e..6d11c51596 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/ListDataDefinition.java
@@ -25,6 +25,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.codehaus.jackson.annotate.JsonCreator;
@@ -86,6 +87,11 @@ public class ListDataDefinition<T extends ToscaDataDefinition> extends ToscaData
((ListDataDefinition)other).listToscaDataDefinition = mapByName.values().stream().collect(Collectors.toList());
return other;
}
-
+
+ @Override
+ public boolean findUidMatch(String uid){
+ return listToscaDataDefinition.stream()
+ .anyMatch(p -> p.findUidMatch(uid));
+ }
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapDataDefinition.java
index 537d9502cd..741aa39230 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/MapDataDefinition.java
@@ -76,5 +76,17 @@ public class MapDataDefinition <T extends ToscaDataDefinition> extends ToscaDa
mapToscaDataDefinition.entrySet().forEach(e -> e.getValue().setOwnerIdIfEmpty(ownerId));
}
}
+
+
+ public String findKeyByItemUidMatch(String uid){
+ if(null == mapToscaDataDefinition)
+ return null;
+ Map.Entry<String, T> entry = mapToscaDataDefinition.entrySet().stream().filter(e ->
+ e.getValue().findUidMatch(uid))
+ .findAny().orElse(null);
+ if(null == entry)
+ return null;
+ return entry.getKey();
+ }
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipInstDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipInstDataDefinition.java
index de9127d08c..0017567031 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipInstDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RelationshipInstDataDefinition.java
@@ -44,12 +44,12 @@ public class RelationshipInstDataDefinition extends ToscaDataDefinition implemen
this.setModificationTime(cdt.getModificationTime());
this.setCapabilityOwnerId(cdt.getCapabilityOwnerId());
this.setRequirementOwnerId(cdt.getRequirementOwnerId());
- this.setCapabiltyId(cdt.getCapabiltyId());
+ this.setCapabilityId(cdt.getCapabilityId());
this.setRequirementId(cdt.getRequirementId());
this.setFromId(cdt.getFromId());
this.setToId(cdt.getToId());
this.setRequirement(cdt.getRequirement());
- this.setCapability(cdt.getCapabilty());
+ this.setCapability(cdt.getCapability());
}
@@ -60,11 +60,11 @@ public class RelationshipInstDataDefinition extends ToscaDataDefinition implemen
public String getRequirement() {
return (String) getToscaPresentationValue(JsonPresentationFields.REQUIREMENT);
}
- public void setCapability(String capabilty) {
- setToscaPresentationValue(JsonPresentationFields.CAPAPILITY, capabilty);
+ public void setCapability(String capability) {
+ setToscaPresentationValue(JsonPresentationFields.CAPAPILITY, capability);
}
- public String getCapabilty() {
+ public String getCapability() {
return (String) getToscaPresentationValue(JsonPresentationFields.CAPAPILITY);
}
public void setToId(Object toId) {
@@ -87,15 +87,15 @@ public class RelationshipInstDataDefinition extends ToscaDataDefinition implemen
setToscaPresentationValue(JsonPresentationFields.REQUIREMENT_ID, requirementId);
}
- public void setCapabiltyId(Object capabiltyId) {
- setToscaPresentationValue(JsonPresentationFields.CAPABILITY_ID, capabiltyId);
+ public void setCapabilityId(Object capabilityId) {
+ setToscaPresentationValue(JsonPresentationFields.CAPABILITY_ID, capabilityId);
}
public String getRequirementId() {
return (String) getToscaPresentationValue(JsonPresentationFields.REQUIREMENT_ID);
}
- public String getCapabiltyId() {
+ public String getCapabilityId() {
return (String) getToscaPresentationValue(JsonPresentationFields.CAPABILITY_ID);
}
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RequirementDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RequirementDataDefinition.java
index 59b14b3060..b32f65f9d3 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RequirementDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/RequirementDataDefinition.java
@@ -191,7 +191,7 @@ public class RequirementDataDefinition extends ToscaDataDefinition implements Se
public int hashCode() {
final int prime = 31;
int result = 1;
- String name = getUniqueId();
+ String name = getName();
String uniqueId = getUniqueId();
String capability = getCapability();
String node = getNode();
@@ -230,7 +230,7 @@ public class RequirementDataDefinition extends ToscaDataDefinition implements Se
return false;
RequirementDataDefinition other = (RequirementDataDefinition) obj;
- String name = getUniqueId();
+ String name = getName();
String uniqueId = getUniqueId();
String capability = getCapability();
String node = getNode();
@@ -308,7 +308,7 @@ public class RequirementDataDefinition extends ToscaDataDefinition implements Se
@Override
public String toString() {
- String name = getUniqueId();
+ String name = getName();
String uniqueId = getUniqueId();
String capability = getCapability();
String node = getNode();
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java
index 9dfc3b602a..d5592995e6 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java
@@ -48,6 +48,9 @@ public enum JsonPresentationFields {
DERIVED_FROM ("derivedFrom", null),
VENDOR_NAME ("vendorName", null),
VENDOR_RELEASE ("vendorRelease", null),
+ RESOURCE_VENDOR_MODEL_NUMBER ("reourceVendorModelNumber",null),
+ SERVICE_TYPE ("serviceType", null),
+ SERVICE_ROLE ("serviceRole", null),
CONFORMANCE_LEVEL ("conformanceLevel", null),
ICON ("icon", null),
TAGS ("tags", null),
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java
index 0d837762e2..36756e9225 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/OriginTypeEnum.java
@@ -27,7 +27,9 @@ public enum OriginTypeEnum {
VFC("VFC", "VFC (Virtual Function Component)", "resource instance", ComponentTypeEnum.RESOURCE),
CP("CP", "CP (Connection Point)", "resource instance", ComponentTypeEnum.RESOURCE),
VL("VL", "VL (Virtual Link)", "resource instance", ComponentTypeEnum.RESOURCE),
- VFCMT("VFCMT", "VFCMT (VFC Monitoring Template)", "resource instance", ComponentTypeEnum.RESOURCE);
+ VFCMT("VFCMT", "VFCMT (VFC Monitoring Template)", "resource instance", ComponentTypeEnum.RESOURCE),
+ CVFC("CVFC", "CVFC (Complex Virtual Function Component)", "resource instance", ComponentTypeEnum.RESOURCE),
+ PNF("PNF", "PNF (Physical Network Function)", "resource instance", ComponentTypeEnum.RESOURCE);
private String value;
private String displayValue;
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java
index d3652c238f..182657e125 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ResourceTypeEnum.java
@@ -27,8 +27,14 @@ package org.openecomp.sdc.be.datatypes.enums;
*/
public enum ResourceTypeEnum {
- VFC("VFC (Virtual Function Component)"), VF("VF"/* (Virtual Function)" */), CP("CP (Connection Point)"),
- VL( "VL (Virtual Link)"), VFCMT("VFCMT (VFC Monitoring Template)"), ABSTRACT("Abstract (Generic VFC/VF/Service Type)");
+ VFC("VFC (Virtual Function Component)"),
+ VF("VF"/* (Virtual Function)" */),
+ CP("CP (Connection Point)"),
+ PNF("PNF"/* (Physical Network Function)" */),
+ CVFC("CVFC"/*Complex Virtual Function Component*/),
+ VL( "VL (Virtual Link)"),
+ VFCMT("VFCMT (VFC Monitoring Template)"),
+ ABSTRACT("Abstract (Generic VFC/VF/PNF/Service Type)");
private String value;
@@ -85,7 +91,7 @@ public enum ResourceTypeEnum {
return false;
}
/**
- * Checks if enum exist with given type ignare case
+ * Checks if enum exist with given type ignore case
* @param type
* @return
*/
diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/tosca/ToscaDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/tosca/ToscaDataDefinition.java
index eba27fb48b..df73adaa4a 100644
--- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/tosca/ToscaDataDefinition.java
+++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/tosca/ToscaDataDefinition.java
@@ -100,4 +100,8 @@ public abstract class ToscaDataDefinition {
return null == dataList? new HashMap<>() : dataList.stream()
.collect(Collectors.toMap(p -> (String)p.getToscaPresentationValue(JsonPresentationFields.NAME), p -> p));
}
+
+ public boolean findUidMatch(String uid){
+ return uid.equals(getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID));
+ }
}
diff --git a/pom.xml b/pom.xml
index b1dfc96bcd..22ff9bbed8 100644
--- a/pom.xml
+++ b/pom.xml
@@ -15,7 +15,7 @@
<!-- ==================== -->
<build.type>-SNAPSHOT</build.type>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <sprint.number>73</sprint.number>
+ <sprint.number>74</sprint.number>
<!-- 3rd parties versions -->
<lang3.version>3.3.2</lang3.version>
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 7cf8d6b7b8..e687804556 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
@@ -22,7 +22,7 @@ beProtocol: http
beSslPort: <%= @ssl_port %>
version: 1.0
released: 2012-11-30
-toscaConformanceLevel: 3.0
+toscaConformanceLevel: 4.0
minToscaConformanceLevel: 3.0
titanCfgFile: /var/lib/jetty/config/catalog-be/titan.properties
@@ -80,6 +80,7 @@ cassandraConfig:
- { name: sdcaudit, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
- { name: sdcartifact, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
- { name: sdccomponent, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
+ - { name: sdcrepository, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
#Application-specific settings of ES
elasticSearch:
@@ -525,6 +526,7 @@ onboarding:
host: <%= @host_ip %>
port: <%= @catalog_port %>
downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+ healthCheckUri: "/onboarding-api/v1.0/healthcheck"
# #GSS IDNS
diff --git a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb
index 4d5f979f56..bc96582615 100644
--- a/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb
+++ b/sdc-os-chef/sdc-cassandra/chef-repo/cookbooks/cassandra-actions/templates/default/configuration.yaml.erb
@@ -22,7 +22,8 @@ beProtocol: http
beSslPort: <%= @ssl_port %>
version: 1.0
released: 2012-11-30
-toscaConformanceLevel: 3.0
+toscaConformanceLevel: 4.0
+minToscaConformanceLevel: 3.0
titanCfgFile: <%= @titan_Path %>/titan.properties
titanInMemoryGraph: false
@@ -80,6 +81,7 @@ cassandraConfig:
- { name: sdcaudit, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
- { name: sdcartifact, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
- { name: sdccomponent, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
+ - { name: sdcrepository, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @dc1 %>','<%= @rep_factor %>']}
#Application-specific settings of ES
elasticSearch:
@@ -519,6 +521,7 @@ onboarding:
host: <%= @host_ip %>
port: <%= @catalog_port %>
downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+ healthCheckUri: "/onboarding-api/v1.0/healthcheck"
# #GSS IDNS
diff --git a/sdc-os-chef/sdc-os-common/templates/default/BE-configuration.yaml.erb b/sdc-os-chef/sdc-os-common/templates/default/BE-configuration.yaml.erb
index b26cd9019c..1fa30f8c49 100644
--- a/sdc-os-chef/sdc-os-common/templates/default/BE-configuration.yaml.erb
+++ b/sdc-os-chef/sdc-os-common/templates/default/BE-configuration.yaml.erb
@@ -22,7 +22,7 @@ beProtocol: http
beSslPort: <%= @ssl_port %>
version: 1.0
released: 2012-11-30
-toscaConformanceLevel: 3.0
+toscaConformanceLevel: 4.0
minToscaConformanceLevel: 3.0
titanCfgFile: <%= @titan_Path %>/titan.properties
@@ -67,7 +67,7 @@ users:
cassandraConfig:
cassandraHosts: [<%= @cassandra_ip %>]
- localDataCenter:
+ localDataCenter: <%= @dc1 %>
reconnectTimeout : 30000
authenticate: true
username: asdc_user
@@ -80,6 +80,8 @@ cassandraConfig:
- { name: sdcaudit, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
- { name: sdcartifact, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
- { name: sdccomponent, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @DC_NAME %>','<%= @rep_factor %>']}
+ - { name: sdcrepository, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @dc1 %>', '<%= @rep_factor %>']}
+ - { name: sdcrepository, replicationStrategy: NetworkTopologyStrategy, replicationInfo: ['<%= @dc1 %>', '<%= @rep_factor %>', '<%= @dc2 %>', '<%= @rep_factor %>']}
#Application-specific settings of ES
elasticSearch:
@@ -140,6 +142,7 @@ resourceTypes: &allResourceTypes
- VF
- VFCMT
- Abstract
+ - CVFC
# validForResourceTypes usage
# validForResourceTypes:
@@ -176,6 +179,8 @@ toscaArtifacts:
#Informational artifacts placeHolder
excludeResourceCategory:
- Generic
+excludeResourceType:
+ - PNF
informationalResourceArtifacts:
features:
displayName: Features
@@ -484,7 +489,15 @@ resourceInformationalArtifacts:
validForResourceTypes: *allResourceTypes
OTHER:
acceptedTypes:
- validForResourceTypes: *allResourceTypes
+ validForResourceTypes:
+ - VFC
+ - CVFC
+ - CP
+ - VL
+ - VF
+ - VFCMT
+ - Abstract
+ - PNF
SNMP_POLL:
acceptedTypes:
validForResourceTypes: *allResourceTypes
@@ -496,6 +509,7 @@ resourceInformationalArtifacts:
validForResourceTypes:
- VF
- VFC
+ - CVFC
resourceInformationalDeployedArtifacts:
@@ -525,6 +539,7 @@ onboarding:
host: <%= @host_ip %>
port: <%= @catalog_port %>
downloadCsarUri: "/onboarding-api/v1.0/vendor-software-products/packages"
+ healthCheckUri: "/onboarding-api/v1.0/healthcheck"
# #GSS IDNS
@@ -584,6 +599,8 @@ 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/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
index 3977f16d5a..ea1c9eff8d 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
@@ -117,19 +117,19 @@ public interface Urls {
// *****************************************ECOMP User
// URL's*****************************************************
- final String ECOMP_PUSH_USER = "http://%s:%s/api/user";
+ final String ECOMP_PUSH_USER = "http://%s:%s/api/v2/user";
- final String ECOMP_EDIT_USER = "http://%s:%s/api/user/%s";
+ final String ECOMP_EDIT_USER = "http://%s:%s/api/v2/user/%s";
- final String ECOMP_GET_USER = "http://%s:%s/api/user/%s";
+ final String ECOMP_GET_USER = "http://%s:%s/api/v2/user/%s";
- final String ECOMP_GET_ALL_USERS = "http://%s:%s/api/users";
+ final String ECOMP_GET_ALL_USERS = "http://%s:%s/api/v2/users";
- final String ECOMP_GET_ALL_AVAILABLE_ROLES = "http://%s:%s/api/roles";
+ final String ECOMP_GET_ALL_AVAILABLE_ROLES = "http://%s:%s/api/v2/roles";
- final String ECOMP_PUSH_USER_ROLES = "http://%s:%s/api/user/%s/roles";
+ final String ECOMP_PUSH_USER_ROLES = "http://%s:%s/api/v2/user/%s/roles";
- final String ECOMP_GET_USER_ROLES = "http://%s:%s/api/user/%s/roles";
+ final String ECOMP_GET_USER_ROLES = "http://%s:%s/api/v2/user/%s/roles";
// *****************************************Elements*************************************************************
final String GET_TAGS_LIST = "http://%s:%s/sdc2/rest/v1/tags";
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java
index b1d04ba88d..537a70984e 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java
@@ -74,7 +74,7 @@ public class ComponentInstanceAttributeTest extends ComponentBaseTest {
.filter(att -> att.getName().equals("private_address")).findAny().get();
// update attribute on vfc instance
final Resource vfWithInsatncePreUpdate = swallowException(
- () -> (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER));
+ () -> (Resource) AtomicOperationUtils.getComponentObject(vf, UserRoleEnum.DESIGNER));
ComponentInstanceProperty attributeOfRI = attributeGetter.apply(vfWithInsatncePreUpdate);
final String newAttValue = "NewValue";
attributeOfRI.setValue(newAttValue);
@@ -86,7 +86,7 @@ public class ComponentInstanceAttributeTest extends ComponentBaseTest {
BaseRestUtils.acceptHeaderData));
// Retrieve updated vf and verify attribute was updated
final Resource vfWithInsatncePostUpdate = swallowException(
- () -> (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER));
+ () -> (Resource) AtomicOperationUtils.getComponentObject(vf, UserRoleEnum.DESIGNER));
ComponentInstanceProperty updatedAttribute = attributeGetter.apply(vfWithInsatncePostUpdate);
assertEquals(updatedAttribute.getValue(), newAttValue);
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 6e36e1b675..45c6b18b59 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
@@ -45,26 +45,33 @@ import org.testng.annotations.Test;
public class AndreyTest {
+ private static ToscaDefinition parseToscaYamlToJavaObject;
+
+
public static void main(String[] args) throws Exception {
ToscaDefinition toscaDefinition;
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 csarPath = new File("C:/Data/D2.0/TOSCA_Ex/Nested.csar");
+// 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"));
+// File path = new File("C:/Data/FileToParse/Definitions/resource-Civfonboarded2016006VvmVvm301607E2100a9b04-template.yml");
+// File csarPath = new File("C:/Data/D2.0/TOSCA_Ex/Nested.csar");
- toscaDefinition = ToscaParserUtils.parseToscaYamlToJavaObject(path);
+
+// toscaDefinition = ToscaParserUtils.parseToscaYamlToJavaObject(path);
System.out.println("listTypeHeatMetaDefinition start " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
- List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition = CsarParserUtils.getListTypeHeatMetaDefinition(csarPath);
+// List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition = CsarParserUtils.getListTypeHeatMetaDefinition(csarPath);
System.out.println("get service start " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
- System.out.println(listTypeHeatMetaDefinition);
- for(TypeHeatMetaDefinition typeHeatMetaDefinition : listTypeHeatMetaDefinition){
- for(GroupHeatMetaDefinition groupHeatMetaDefinition : typeHeatMetaDefinition.getGroupHeatMetaDefinition()){
- List<HeatMetaFirstLevelDefinition> artifactList = groupHeatMetaDefinition.getArtifactList();
- boolean isBase = groupHeatMetaDefinition.getPropertyHeatMetaDefinition().getValue();
- }
-
- }
+// System.out.println(listTypeHeatMetaDefinition);
+// for(TypeHeatMetaDefinition typeHeatMetaDefinition : listTypeHeatMetaDefinition){
+// for(GroupHeatMetaDefinition groupHeatMetaDefinition : typeHeatMetaDefinition.getGroupHeatMetaDefinition()){
+// List<HeatMetaFirstLevelDefinition> artifactList = groupHeatMetaDefinition.getArtifactList();
+// boolean isBase = groupHeatMetaDefinition.getPropertyHeatMetaDefinition().getValue();
+// }
+//
+// }
System.out.println("Finished");
System.out.println("get service start " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
}
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java
index c52ee470cf..66bc153e70 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java
@@ -238,7 +238,7 @@ public class BasicHttpAuthenticationTest extends ComponentBaseTest {
assertTrue(restResponse.getHeaderFields().containsKey(WWW_AUTHENTICATE));
List<String> getAuthenticateHeader = restResponse.getHeaderFields().get(WWW_AUTHENTICATE);
assertEquals("www-authenticate header contains more then one value", 1, getAuthenticateHeader.size());
- assertTrue(getAuthenticateHeader.get(0).equals("Basic realm=" + "\"ASDC\""));
+ assertTrue(getAuthenticateHeader.get(0).equals("Basic realm=" + "\"SDC\""));
validateAuditAuthentication("", AUTH_REQUIRED, ComponentTypeEnum.SERVICE);
}
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java
index 8ce8dc5433..b460b9fce0 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java
@@ -1816,8 +1816,8 @@ public class ImportToscaResourceTest extends ComponentBaseTest {
importReqDetailsFather.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
}
- // DE202329
- @Test(enabled = false)
+ // DE202329 - TDP -154379
+ @Test(enabled = true)
public void requirementWithMissingTypeTest() throws Exception {
String fatherName = "father";
String fatherFileName = "DerivedFromWebApplication_HasNoReqType.yml";
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java
index 0a7b4a98aa..a33ee71f9e 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java
@@ -86,7 +86,7 @@ public class MultipleResourceUpdate extends ComponentBaseTest {
ComponentInstance instanceCP2 = AtomicOperationUtils
.addComponentInstanceToComponentContainer(cp2, vf, UserRoleEnum.DESIGNER, true).left().value();
- vf = (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER);
+ vf = (Resource) AtomicOperationUtils.getComponentObject(vf, UserRoleEnum.DESIGNER);
// Create Vertex(Link/Associate 2 Resource Instances on Canvas)
AtomicOperationUtils.associate2ResourceInstances(vf, instanceCP1, instanceVL, AssocType.LINKABLE.getAssocType(),
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java
index 5a89a6766c..18b2329663 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java
@@ -111,7 +111,7 @@ public class ToscaDefinition {
typeDescription.putMapPropertyType("metadata", String.class, String.class);
// TODO Andrey imports format
typeDescription.putMapPropertyType("imports", String.class, ToscaImportsDefinition.class);
- typeDescription.putListPropertyType("imports", List.class);
+// typeDescription.putListPropertyType("imports", List.class);
typeDescription.putMapPropertyType("node_types", String.class, ToscaNodeTypesDefinition.class);
return typeDescription;
}
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaParameterConstants.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaParameterConstants.java
new file mode 100644
index 0000000000..18d7d7d97b
--- /dev/null
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaParameterConstants.java
@@ -0,0 +1,9 @@
+package org.openecomp.sdc.ci.tests.tosca.datatypes;
+
+public interface ToscaParameterConstants {
+
+ public static final String ENTRY_DEFINITION = "Entry-Definitions";
+ public static final String TOSCA_META_PATH = "TOSCA-Metadata/TOSCA.meta";
+ public static final String HEAT_META_PATH = "Artifacts/HEAT.meta";
+ public static final String IMPORT_STRUCTURE = "importStructure";
+}
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java
index 69c8b2fe2f..cd6687be0e 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/CsarParserUtils.java
@@ -30,11 +30,13 @@ import java.util.Set;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
import org.openecomp.sdc.ci.tests.datatypes.GroupHeatMetaDefinition;
import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition;
import org.openecomp.sdc.ci.tests.datatypes.PropertyHeatMetaDefinition;
import org.openecomp.sdc.ci.tests.datatypes.TypeHeatMetaDefinition;
import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaParameterConstants;
import org.openecomp.sdc.ci.tests.utils.validation.CsarValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -42,40 +44,34 @@ import org.slf4j.LoggerFactory;
public class CsarParserUtils {
private static Logger log = LoggerFactory.getLogger(CsarValidationUtils.class.getName());
- public static List<TypeHeatMetaDefinition> getListTypeHeatMetaDefinition(File csarUUID) throws Exception {
-
- String artifactHeatMetaLocation = "Artifacts/HEAT.meta";
- JSONParser parser = new JSONParser();
- String csarPayload = CsarValidationUtils.getCsarPayload(csarUUID, artifactHeatMetaLocation);
- if (csarPayload != null) {
- Object parse = parser.parse(csarPayload);
- JSONObject jsonObject = (JSONObject) parse;
- JSONObject jsonObjectImportStructure = (JSONObject) jsonObject.get("importStructure");
- List<TypeHeatMetaDefinition> listHeatMetaDefenition = new ArrayList<TypeHeatMetaDefinition>();
- listHeatMetaDefenition = getArtifactsByGroup(jsonObjectImportStructure, listHeatMetaDefenition);
- return listHeatMetaDefenition;
- }
- return null;
+ public static List<TypeHeatMetaDefinition> getListTypeHeatMetaDefinition(File csarFileLocation) throws Exception {
+ String artifactHeatMetaLocation = ToscaParameterConstants.HEAT_META_PATH;
+ String csarPayload = ToscaParserUtils.getYamlPayloadFromCsar(csarFileLocation, artifactHeatMetaLocation);
+ return getListTypeHeatMetaDefinitionByPayload(csarPayload);
}
-
+
public static List<TypeHeatMetaDefinition> getListTypeHeatMetaDefinition(String csarUUID) throws Exception {
+
+ String artifactHeatMetaLocation = ToscaParameterConstants.HEAT_META_PATH;
+ String csarPayload = ToscaParserUtils.getCsarPayload(csarUUID, artifactHeatMetaLocation);
+ return getListTypeHeatMetaDefinitionByPayload(csarPayload);
+ }
- String artifactHeatMetaLocation = "Artifacts/HEAT.meta";
+ public static List<TypeHeatMetaDefinition> getListTypeHeatMetaDefinitionByPayload(String csarPayload) throws ParseException {
JSONParser parser = new JSONParser();
- String csarPayload = CsarValidationUtils.getCsarPayload(csarUUID, artifactHeatMetaLocation);
if (csarPayload != null) {
Object parse = parser.parse(csarPayload);
JSONObject jsonObject = (JSONObject) parse;
- JSONObject jsonObjectImportStructure = (JSONObject) jsonObject.get("importStructure");
+ JSONObject jsonObjectImportStructure = (JSONObject) jsonObject.get(ToscaParameterConstants.IMPORT_STRUCTURE);
List<TypeHeatMetaDefinition> listHeatMetaDefenition = new ArrayList<TypeHeatMetaDefinition>();
listHeatMetaDefenition = getArtifactsByGroup(jsonObjectImportStructure, listHeatMetaDefenition);
return listHeatMetaDefenition;
}
return null;
-
}
+
protected static List<TypeHeatMetaDefinition> getArtifactsByGroup(JSONObject jsonObjectImportStructure, List<TypeHeatMetaDefinition> listHeatMetaDefenition) {
@SuppressWarnings("unchecked")
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java
index 26fac7fd6e..3bae41fc57 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java
@@ -21,19 +21,30 @@
package org.openecomp.sdc.ci.tests.utils;
import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
import java.io.File;
import java.io.FileInputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.Map;
import java.util.Set;
import org.openecomp.sdc.ci.tests.datatypes.enums.ToscaKeysEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition;
import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaGroupsTopologyTemplateDefinition;
import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaNodeTemplatesTopologyTemplateDefinition;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaParameterConstants;
import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaSubstitutionMappingsDefinition;
import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaTopologyTemplateDefinition;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils;
import org.openecomp.sdc.ci.tests.utils.validation.CsarValidationUtils;
+import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray;
+import org.openecomp.sdc.common.util.ZipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.TypeDescription;
@@ -45,20 +56,56 @@ public class ToscaParserUtils {
private static Logger log = LoggerFactory.getLogger(ToscaParserUtils.class.getName());
- public static ToscaDefinition parseToscaYamlToJavaObject(String csarUUID) throws Exception {
+
+ /**method get csarUUID and send GET API request toward BE
+ * @param csarUUID
+ * @return
+ * @throws Exception
+ */
+ public static ToscaDefinition parseToscaYamlToJavaObjectByCsarUuid(String csarUUID) throws Exception {
ToscaDefinition toscaDefinition = null;
- String TOSCAMetaLocation = "TOSCA-Metadata/TOSCA.meta";
+ String TOSCAMetaLocation = ToscaParameterConstants.TOSCA_META_PATH;
Map<?, ?> map = getToscaYamlMap(csarUUID, TOSCAMetaLocation);
assertNotNull("Tosca Entry-Definitions is null", map);
if (map != null) {
- File definitionYamlLocation = (File) map.get("Entry-Definitions");
+ File definitionYamlLocation = (File) map.get(ToscaParameterConstants.ENTRY_DEFINITION);
toscaDefinition = parseToscaYamlToJavaObject(definitionYamlLocation);
}
return toscaDefinition;
}
+ /**method read csar from location
+ * @param csarNameLocation - full path with csar name
+ * @return
+ * @throws Exception
+ */
+ public static ToscaDefinition parseToscaMainYamlToJavaObjectByCsarLocation(File csarNameLocation) throws Exception {
+
+ ToscaDefinition toscaDefinition = null;
+ String TOSCAMetaLocation = ToscaParameterConstants.TOSCA_META_PATH;
+// read file location of main yaml file(location+name) from TOSCA.meta file by
+ Map<?, ?> map = getToscaYamlMap(csarNameLocation, TOSCAMetaLocation);
+
+ assertNotNull("Tosca Entry-Definitions is null", map);
+
+ String definitionYamlLocation = (String) map.get(ToscaParameterConstants.ENTRY_DEFINITION);
+ String csarPayload = getYamlPayloadFromCsar(csarNameLocation, definitionYamlLocation);
+ toscaDefinition = parseToscaYamlPayloadToJavaObject(csarPayload);
+ return toscaDefinition;
+
+ }
+
+ public static ToscaDefinition parseToscaAnyYamlToJavaObjectByCsarLocation(File csarNameLocation, String yamlLocation) throws Exception {
+
+ ToscaDefinition toscaDefinition = null;
+ String csarPayload = getYamlPayloadFromCsar(csarNameLocation, yamlLocation);
+ toscaDefinition = parseToscaYamlPayloadToJavaObject(csarPayload);
+ return toscaDefinition;
+
+ }
+
public static ToscaDefinition parseToscaYamlToJavaObject(File path) throws Exception {
ToscaDefinition toscaDefinition = null;
@@ -72,7 +119,7 @@ public class ToscaParserUtils {
System.out.println("Exception: " + e);
}
- Constructor constructor = getConstructor();
+ Constructor constructor = initToscaDefinitionObject();
Yaml yaml = new Yaml(constructor);
try {
@@ -90,7 +137,7 @@ public class ToscaParserUtils {
public static ToscaDefinition parseToscaYamlPayloadToJavaObject(String payload){
ToscaDefinition toscaDefinition = null;
- Constructor constructor = getConstructor();
+ Constructor constructor = initToscaDefinitionObject();
Yaml yaml = new Yaml(constructor);
try {
@@ -104,23 +151,33 @@ public class ToscaParserUtils {
}
- public static Constructor getConstructor() {
- Constructor constructor = new Constructor(ToscaDefinition.class);
- constructor.addTypeDescription(ToscaDefinition.getTypeDescription());
- constructor.addTypeDescription(ToscaTopologyTemplateDefinition.getTypeDescription());
- constructor.addTypeDescription(ToscaNodeTemplatesTopologyTemplateDefinition.getTypeDescription());
- constructor.addTypeDescription(ToscaGroupsTopologyTemplateDefinition.getTypeDescription());
- constructor.addTypeDescription(ToscaSubstitutionMappingsDefinition.getTypeDescription());
+ public static Constructor initToscaDefinitionObject() {
+ Constructor toscaStructure = new Constructor(ToscaDefinition.class);
+ toscaStructure.addTypeDescription(ToscaDefinition.getTypeDescription());
+ toscaStructure.addTypeDescription(ToscaTopologyTemplateDefinition.getTypeDescription());
+ toscaStructure.addTypeDescription(ToscaNodeTemplatesTopologyTemplateDefinition.getTypeDescription());
+ toscaStructure.addTypeDescription(ToscaGroupsTopologyTemplateDefinition.getTypeDescription());
+ toscaStructure.addTypeDescription(ToscaSubstitutionMappingsDefinition.getTypeDescription());
// Skip properties which are found in YAML, but not found in POJO
PropertyUtils propertyUtils = new PropertyUtils();
propertyUtils.setSkipMissingProperties(true);
- constructor.setPropertyUtils(propertyUtils);
- return constructor;
+ toscaStructure.setPropertyUtils(propertyUtils);
+ return toscaStructure;
}
- public static Map<?, ?> getToscaYamlMap(String csarUUID, String fileLocation) throws Exception {
- String csarPayload = CsarValidationUtils.getCsarPayload(csarUUID, fileLocation);
+ public static Map<?, ?> getToscaYamlMap(String csarUUID, String yamlFileLocation) throws Exception {
+ String csarPayload = getCsarPayload(csarUUID, yamlFileLocation);
+ if (csarPayload != null) {
+ Yaml yaml = new Yaml();
+ Map<?, ?> map = (Map<?, ?>) yaml.load(csarPayload);
+ return map;
+ }
+ return null;
+ }
+
+ public static Map<?, ?> getToscaYamlMap(File csarPath, String yamlFileLocation) throws Exception {
+ String csarPayload = getYamlPayloadFromCsar(csarPath, yamlFileLocation);
if (csarPayload != null) {
Yaml yaml = new Yaml();
Map<?, ?> map = (Map<?, ?>) yaml.load(csarPayload);
@@ -129,6 +186,39 @@ public class ToscaParserUtils {
return null;
}
+
+ public static String getCsarPayload(String csarName, String yamlFileLocation) throws Exception {
+
+ RestResponseAsByteArray csar = ImportRestUtils.getCsar(csarName, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ assertTrue("Return response code different from 200", csar.getHttpStatusCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ byte[] data = csar.getResponse();
+ return getDataFromZipFileByBytes(yamlFileLocation, data);
+
+ }
+
+ public static String getYamlPayloadFromCsar(File csarName, String fileLocation) throws Exception {
+
+ Path path = csarName.toPath();
+ byte[] data = Files.readAllBytes(path);
+ return getDataFromZipFileByBytes(fileLocation, data);
+
+ }
+
+ /** method get file data from zip data by file location in the zip structure
+ * @param fileLocation
+ * @param data
+ * @return
+ */
+ public static String getDataFromZipFileByBytes(String fileLocation, byte[] data) {
+ Map<String, byte[]> readZip = null;
+ if (data != null && data.length > 0) {
+ readZip = ZipUtil.readZip(data);
+
+ }
+ byte[] artifactsBs = readZip.get(fileLocation);
+ String str = new String(artifactsBs, StandardCharsets.UTF_8);
+ return str;
+ }
/* public static Map<?, ?> getToscaYamlMap(String csarUUID, String fileLocation) throws Exception {
String csarPayload = CsarValidationUtils.getCsarPayload(csarUUID, fileLocation);
if (csarPayload != null) {
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java
index 207c4bbe02..17148ce8a9 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java
@@ -261,7 +261,7 @@ public final class AtomicOperationUtils {
LifeCycleStatesEnum curentCompState = LifeCycleStatesEnum.findByCompState(component.getLifecycleState().toString());
if (curentCompState == targetState) {
- component = getCompoenntObject(component, userRole);
+ component = getComponentObject(component, userRole);
return Pair.of(component, null);
}
// List<LifeCycleStatesEnum> lifeCycleStatesEnumOrigList = new
@@ -299,7 +299,7 @@ public final class AtomicOperationUtils {
}
}
- Component componentJavaObject = getCompoenntObject(component, userRole);
+ Component componentJavaObject = getComponentObject(component, userRole);
if (validateState == true && isValidationFailed == true) {
assertTrue("change state failed" + lifeCycleStatesResponse.getResponse(), false);
@@ -431,6 +431,12 @@ public final class AtomicOperationUtils {
Service container = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
return container;
}
+
+ public static Service getServiceObject(String uniqueId) throws Exception {
+ RestResponse serviceResponse = ServiceRestUtils.getService(uniqueId);
+ Service container = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
+ return container;
+ }
public static Product getProductObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
User defaultUser = ElementFactory.getDefaultUser(userRole);
@@ -439,7 +445,7 @@ public final class AtomicOperationUtils {
return container;
}
- public static Component getCompoenntObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
+ public static Component getComponentObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
User defaultUser = ElementFactory.getDefaultUser(userRole);
switch (containerDetails.getComponentType()) {
@@ -521,7 +527,7 @@ public final class AtomicOperationUtils {
if (changeComponentInstanceVersionResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
- Component compoenntObject = AtomicOperationUtils.getCompoenntObject(containerDetails, userRole);
+ Component compoenntObject = AtomicOperationUtils.getComponentObject(containerDetails, userRole);
ComponentInstance componentInstanceJavaObject = ResponseParser.convertComponentInstanceResponseToJavaObject(changeComponentInstanceVersionResp.getResponse());
return Either.left(Pair.of(compoenntObject, componentInstanceJavaObject));
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 25fce34a75..e387cd2544 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
@@ -21,8 +21,7 @@
package org.openecomp.sdc.ci.tests.utils.rest;
import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
+import java.util.*;
import org.openecomp.sdc.ci.tests.api.Urls;
import org.openecomp.sdc.ci.tests.config.Config;
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java
index d53d2da91b..22a352cbfe 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java
@@ -262,19 +262,14 @@ public class LifecycleRestUtils extends BaseRestUtils {
LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception {
Config config = Utils.getConfig();
String url = String.format(Urls.CHANGE_COMPONENT_LIFECYCLE_STATE, config.getCatalogBeHost(),
- config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()),
- component.getUniqueId(), LifeCycleStatesEnum);
- RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(COMMENT),
- sdncModifierDetails.getUserId(), acceptHeaderData);
+ config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId(), LifeCycleStatesEnum);
+ RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(COMMENT), sdncModifierDetails.getUserId(), acceptHeaderData);
if (LifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) {
- String productUniqueId = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId");
+ String productUniqueId = ResponseParser.getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId");
component.setUniqueId(productUniqueId);
- String productVersion = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version");
+ String productVersion = ResponseParser.getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version");
component.setVersion(productVersion);
- String newLifecycleState = ResponseParser
- .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState");
+ String newLifecycleState = ResponseParser.getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState");
component.setLifecycleState(LifecycleStateEnum.valueOf(newLifecycleState));
}
return LifeCycleStatesEnumServiceResponse;
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java
index ad9f482bc1..95953838c9 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java
@@ -60,6 +60,7 @@ import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
import org.openecomp.sdc.ci.tests.datatypes.ServiceDistributionStatus;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.google.gson.Gson;
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java
index a93587dbbc..9ba4a906c6 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java
@@ -94,6 +94,7 @@ public class ServiceRestUtils extends BaseRestUtils {
}
public static RestResponse createService(ServiceReqDetails service, User user) throws Exception {
+
Config config = Utils.getConfig();
String url = String.format(Urls.CREATE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort());
String serviceBodyJson = gson.toJson(service);
@@ -256,6 +257,7 @@ public class ServiceRestUtils extends BaseRestUtils {
config.getCatalogBePort(), serviceName, serviceVersion);
RestResponse deleteResponse = http.httpSendDelete(url, headersMap);
+ deleteMarkedServices(sdncModifierDetails.getUserId());
return deleteResponse;
}
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java
index 0fe11537e4..7423dbc808 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java
@@ -44,39 +44,6 @@ import org.openecomp.sdc.common.util.ZipUtil;
public class CsarValidationUtils {
- public static String getCsarPayload(String csarName, String fileLocation) throws Exception {
-
- RestResponseAsByteArray csar = ImportRestUtils.getCsar(csarName, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
- assertTrue("Return response code different from 200", csar.getHttpStatusCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
- Map<String, byte[]> readZip = null;
- byte[] data = csar.getResponse();
- if (data != null && data.length > 0) {
- readZip = ZipUtil.readZip(data);
-
- }
- byte[] artifactsBs = readZip.get(fileLocation);
- String str = new String(artifactsBs, StandardCharsets.UTF_8);
- return str;
-
- }
-
- public static String getCsarPayload(File csarName, String fileLocation) throws Exception {
-
-// RestResponseAsByteArray csar = ImportRestUtils.getCsar(csarName, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
-// assertTrue("Return response code different from 200", csar.getHttpStatusCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
- Map<String, byte[]> readZip = null;
- Path path = csarName.toPath();
-
- byte[] data = Files.readAllBytes(path);
- if (data != null && data.length > 0) {
- readZip = ZipUtil.readZip(data);
- }
- byte[] artifactsBs = readZip.get(fileLocation);
- String str = new String(artifactsBs, StandardCharsets.UTF_8);
- return str;
-
- }
-
public static void validateCsarVfArtifact(String csarUUID, Resource resource) throws Exception {
List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition = CsarParserUtils.getListTypeHeatMetaDefinition(csarUUID);
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 a680990af8..127ae54784 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
@@ -80,7 +80,6 @@ import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
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.AutomationUtils;
import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
import org.openecomp.sdc.ci.tests.utils.validation.DistributionValidationUtils;
@@ -356,42 +355,45 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// create component/s & upload artifact via external api
if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) {
component = getComponentWithResourceInstanceInTargetLifeCycleState(chosenLifeCycleState, resourceTypeEnum);
-
restResponse = uploadArtifactOfRIIncludingValiditionOfAuditAndResponseCode(component, component.getComponentInstances().get(0), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, 200);
- component =AtomicOperationUtils.getCompoenntObject(component, UserRoleEnum.DESIGNER);
-
- if((LifeCycleStatesEnum.CERTIFICATIONREQUEST == chosenLifeCycleState) && (!component.getComponentType().toString().equals(ComponentTypeEnum.RESOURCE.toString()))) {
-// numberOfArtifact = component.getComponentInstances().get(0).getDeploymentArtifacts().size();
- numberOfArtifact = (component.getComponentInstances().get(0).getDeploymentArtifacts() == null ? 0 : component.getComponentInstances().get(0).getDeploymentArtifacts().size());
- } else {
-// numberOfArtifact = component.getComponentInstances().get(0).getDeploymentArtifacts().size() + 1;
- numberOfArtifact = (component.getComponentInstances().get(0).getDeploymentArtifacts() == null ? 0 : component.getComponentInstances().get(0).getDeploymentArtifacts().size());
- }
+ component = getNewerVersionOfComponent(component, chosenLifeCycleState);
+ numberOfArtifact = (component.getComponentInstances().get(0).getDeploymentArtifacts() == null ? 0 : component.getComponentInstances().get(0).getDeploymentArtifacts().size());
} else {
component = getComponentInTargetLifeCycleState(componentTypeEnum.toString(), UserRoleEnum.DESIGNER, chosenLifeCycleState, resourceTypeEnum);
-
restResponse = uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, 200);
- numberOfArtifact = component.getDeploymentArtifacts().size() + 1;
+ component = updateComponentDetailsByLifeCycleState(chosenLifeCycleState, component);
+ numberOfArtifact = component.getDeploymentArtifacts().size();
}
-
-
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
- component = getNewerVersionOfComponent(component, chosenLifeCycleState);
-
// Get list of deployment artifact + download them via external API
Map<String, ArtifactDefinition> deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum);
- Assert.assertEquals(numberOfArtifact, deploymentArtifacts.keySet().size(), "Expected that number of deployment artifact will be increase by one.");
+ Assert.assertEquals(numberOfArtifact, deploymentArtifacts.keySet().size(), "Expected that number of deployment artifacts will be increase by one.");
// Download the uploaded artifact via external API
downloadResourceDeploymentArtifactExternalAPI(component, deploymentArtifacts.get(responseArtifact.getArtifactLabel()), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentTypeEnum);
-
+ return component;
+ }
+
+ /**
+ * according lifecycle state of component get updated component details
+ * @param chosenLifeCycleState
+ * @param component
+ * @return
+ * @throws Exception
+ */
+ public Component updateComponentDetailsByLifeCycleState(LifeCycleStatesEnum chosenLifeCycleState, Component component) throws Exception {
+ if(LifeCycleStatesEnum.CHECKOUT.equals(chosenLifeCycleState)){
+ component = AtomicOperationUtils.getComponentObject(component, UserRoleEnum.DESIGNER);
+ }else{
+ component = getNewerVersionOfComponent(component, chosenLifeCycleState);
+ }
return component;
}
// Upload artifact via external API + Check auditing for upload operation + Check response of external API
- public RestResponse uploadArtifactOfRIIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, ComponentInstance componentInstance, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, Integer expectedResponseCode) throws Exception {
- RestResponse restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, resourceDetails.getComponentInstances().get(0));
+ public RestResponse uploadArtifactOfRIIncludingValiditionOfAuditAndResponseCode(Component component, ComponentInstance componentInstance, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, Integer expectedResponseCode) throws Exception {
+ RestResponse restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, component.getComponentInstances().get(0));
// Check response of external API
Integer responseCode = restResponse.getErrorCode();
@@ -406,18 +408,16 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentInstance.getNormalizedName());
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts");
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts");
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);
return restResponse;
}
-
-
protected Component getComponentWithResourceInstanceInTargetLifeCycleState(LifeCycleStatesEnum lifeCycleStatesEnum, ResourceTypeEnum resourceTypeEnum) throws Exception {
Component component;
if(resourceTypeEnum == ResourceTypeEnum.VF) {
@@ -426,9 +426,9 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Component resourceInstanceDetails = getComponentInTargetLifeCycleState(ComponentTypeEnum.RESOURCE.getValue(), UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, null);
AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceInstanceDetails, component, UserRoleEnum.DESIGNER, true).left().value();
- // Add artifact to service if asked for certifcationrequest - must be at least one artifact for the flow
- if((LifeCycleStatesEnum.CERTIFICATIONREQUEST == lifeCycleStatesEnum) || (LifeCycleStatesEnum.STARTCERTIFICATION == lifeCycleStatesEnum)) {
- }
+ // Add artifact to service if asked for certification request - must be at least one artifact for the flow
+// if((LifeCycleStatesEnum.CERTIFICATIONREQUEST == lifeCycleStatesEnum) || (LifeCycleStatesEnum.STARTCERTIFICATION == lifeCycleStatesEnum)) {
+// }
AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, component, UserRoleEnum.DESIGNER, true, true).left().value();
component = AtomicOperationUtils.changeComponentState(component, UserRoleEnum.DESIGNER, lifeCycleStatesEnum, true).getLeft();
} else {
@@ -446,8 +446,8 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// Upload artifact via external API + Check auditing for upload operation + Check response of external API
- protected RestResponse uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, Integer expectedResponseCode) throws Exception {
- RestResponse restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails, sdncModifierDetails, artifactReqDetails);
+ protected RestResponse uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, Integer expectedResponseCode) throws Exception {
+ RestResponse restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(component, sdncModifierDetails, artifactReqDetails);
// Check response of external API
Integer responseCode = restResponse.getErrorCode();
@@ -460,10 +460,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);
return restResponse;
@@ -478,7 +478,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// check that this version different for input version
// check that this component uniqueID different from input uniqueID
// Return: that version
- protected Component getNewerVersionOfComponent(Component component, LifeCycleStatesEnum lifeCycleStatesEnum) throws Exception {
+ protected synchronized Component getNewerVersionOfComponent(Component component, LifeCycleStatesEnum lifeCycleStatesEnum) throws Exception {
Component resourceDetails = null;
if((!lifeCycleStatesEnum.equals(LifeCycleStatesEnum.CHECKOUT)) && (!lifeCycleStatesEnum.equals(LifeCycleStatesEnum.STARTCERTIFICATION))) {
@@ -501,7 +501,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
System.out.println("Service UniqueID: " + resourceDetails.getUniqueId());
// Checking that new version exist + different from old one by unique id
- Assert.assertNotEquals(resourceVersion, resourceNewVersion, "Expected for diffrent resource version.");
+ Assert.assertNotEquals(resourceVersion, resourceNewVersion, "Expected for different resource version.");
Assert.assertNotEquals(resourceUniqueID, resourceNewUniqueID, "Expected that resource will have new unique ID.");
} else {
if(component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
@@ -518,13 +518,13 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// download deployment via external api + check response code for success (200) + get artifactReqDetails and verify payload + verify audit
- protected RestResponse downloadResourceDeploymentArtifactExternalAPI(Component resourceDetails, ArtifactDefinition artifactDefinition, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, ComponentTypeEnum componentTypeEnum) throws Exception {
+ protected RestResponse downloadResourceDeploymentArtifactExternalAPI(Component component, ArtifactDefinition artifactDefinition, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, ComponentTypeEnum componentTypeEnum) throws Exception {
RestResponse restResponse;
if(componentTypeEnum == ComponentTypeEnum.RESOURCE_INSTANCE) {
- restResponse = ArtifactRestUtils.getComponentInstanceDeploymentArtifactExternalAPI(resourceDetails.getUUID(), resourceDetails.getComponentInstances().get(0).getNormalizedName(), artifactDefinition.getArtifactUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getComponentType().toString());
+ restResponse = ArtifactRestUtils.getComponentInstanceDeploymentArtifactExternalAPI(component.getUUID(), component.getComponentInstances().get(0).getNormalizedName(), artifactDefinition.getArtifactUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), component.getComponentType().toString());
} else {
- restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceDetails.getUUID(), artifactDefinition.getArtifactUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getComponentType().toString());
+ restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(component.getUUID(), artifactDefinition.getArtifactUUID(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), component.getComponentType().toString());
}
Integer responseCode = restResponse.getErrorCode();
@@ -532,7 +532,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Assert.assertEquals(responseCode,expectedCode, "Response code is not correct.");
- // For known artifact/payload - verify payload of downloaded artfaict
+ // For known artifact/payload - verify payload of downloaded artifact
if (artifactReqDetails != null) {
String response = restResponse.getResponse();
String payloadData = artifactReqDetails.getPayload();
@@ -575,8 +575,8 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
// download deployment via external api + check response code for success (200) + verify audit
- protected void downloadResourceDeploymentArtifactExternalAPI(Component resourceDetails, ArtifactDefinition artifactDefinition, User sdncModifierDetails) throws Exception {
- downloadResourceDeploymentArtifactExternalAPI(resourceDetails, artifactDefinition, sdncModifierDetails, null, resourceDetails.getComponentType());
+ protected void downloadResourceDeploymentArtifactExternalAPI(Component component, ArtifactDefinition artifactDefinition, User sdncModifierDetails) throws Exception {
+ downloadResourceDeploymentArtifactExternalAPI(component, artifactDefinition, sdncModifierDetails, null, component.getComponentType());
}
@@ -821,13 +821,13 @@ public class CRUDExternalAPI extends ComponentBaseTest {
{LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithSameLabel"},
-// DE306360 {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
+ {LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.SERVICE, "uploadArtifactWithSameLabel"},
-// DE306360 {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
+ {LifeCycleStatesEnum.CHECKIN, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.SERVICE, "uploadArtifactWithSameLabel"},
-// DE306360 {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
+ {LifeCycleStatesEnum.CERTIFICATIONREQUEST, ComponentTypeEnum.RESOURCE_INSTANCE, "uploadArtifactWithSameLabel"},
{LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.RESOURCE, "uploadArtifactWithInvalidCheckSum"},
{LifeCycleStatesEnum.CHECKOUT, ComponentTypeEnum.SERVICE, "uploadArtifactWithInvalidCheckSum"},
@@ -902,104 +902,104 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
// Upload artifact with invalid type via external API - to long type
- protected void uploadArtifactWithInvalidTypeToLong(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidTypeToLong(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
artifactReqDetails.setArtifactType("dsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfdsdsfdsfds");
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name());
List<String> variables = asList(artifactReqDetails.getArtifactType());
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with invalid type via external API - empty type
- protected void uploadArtifactWithInvalidTypeEmpty(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidTypeEmpty(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
artifactReqDetails.setArtifactType("");
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name());
List<String> variables = asList(artifactReqDetails.getArtifactType());
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with invalid checksum via external API
- protected void uploadArtifactWithInvalidCheckSum(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidCheckSum(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_INVALID_MD5.name());
List<String> variables = asList();
- uploadArtifactWithInvalidCheckSumOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactWithInvalidCheckSumOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables);
}
// Upload artifact with valid type & invalid name via external API - name to long
- protected void uploadArtifactWithInvalidNameToLong(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidNameToLong(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name());
List<String> variables = asList("artifact name", "255");
artifactReqDetails.setArtifactName("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with valid type & invalid name via external API - name is empty
- protected void uploadArtifactWithInvalidNameEmpty(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidNameEmpty(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_ARTIFACT_NAME.name());
List<String> variables = asList();
artifactReqDetails.setArtifactName("");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with valid type & invalid label via external API - label to long
- protected void uploadArtifactWithInvalidLabelToLong(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidLabelToLong(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name());
List<String> variables = asList("artifact label", "255");
artifactReqDetails.setArtifactLabel("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with valid type & invalid label via external API - label is empty
- protected void uploadArtifactWithInvalidLabelEmpty(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidLabelEmpty(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
List<String> variables = asList("artifact label");
artifactReqDetails.setArtifactLabel("");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with invalid description via external API - to long description
- protected void uploadArtifactWithInvalidDescriptionToLong(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidDescriptionToLong(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.EXCEEDS_LIMIT.name());
List<String> variables = asList("artifact description", "256");
artifactReqDetails.setDescription("invalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeinvalGGfdsiofhdsouhfoidshfoidshoifhsdoifhdsouihfdsofhiufdsghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidTypeghiufghodhfioudsgafodsgaiofudsghifudsiugfhiufawsouipfhgawseiupfsadiughdfsoiuhgfaighfpasdghfdsaqgfdsgdfgidType");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
// Upload artifact with invalid description via external API - empty description
- protected void uploadArtifactWithInvalidDescriptionEmpty(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithInvalidDescriptionEmpty(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
List<String> variables = asList("artifact description");
artifactReqDetails.setDescription("");
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
@@ -1007,14 +1007,14 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// Upload artifact with same label via external API
- protected void uploadArtifactWithSameLabel(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected void uploadArtifactWithSameLabel(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
ComponentInstance componentResourceInstanceDetails) throws Exception {
RestResponse restResponse = null;
if(componentResourceInstanceDetails != null) {
- restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails);
+ restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails);
} else {
- restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails);
+ restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails);
}
@@ -1022,18 +1022,18 @@ public class CRUDExternalAPI extends ComponentBaseTest {
ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_EXIST.name());
List<String> variables = asList(artifactDefinition.getArtifactDisplayName());
- uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
artifactReqDetails, 400, componentResourceInstanceDetails, errorInfo, variables, null, false);
}
- protected RestResponse uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected RestResponse uploadArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
Integer expectedResponseCode, ComponentInstance componentResourceInstanceDetails, ErrorInfo errorInfo, List<String> variables, LifeCycleStatesEnum lifeCycleStatesEnum, Boolean includeResourceNameInAudit) throws Exception {
RestResponse restResponse;
if(componentResourceInstanceDetails != null) {
- restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(resourceDetails, sdncModifierDetails, artifactReqDetails, componentResourceInstanceDetails);
+ restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(component, sdncModifierDetails, artifactReqDetails, componentResourceInstanceDetails);
} else {
- restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails, sdncModifierDetails, artifactReqDetails);
+ restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(component, sdncModifierDetails, artifactReqDetails);
}
@@ -1046,30 +1046,30 @@ public class CRUDExternalAPI extends ComponentBaseTest {
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
// ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
responseArtifact.setUpdaterFullName("");
responseArtifact.setUserIdLastUpdater(sdncModifierDetails.getUserId());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, resourceDetails.getUUID(), errorInfo, variables);
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- expectedExternalAudit.setRESOURCE_TYPE(resourceDetails.getComponentType().getValue());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, component.getUUID(), errorInfo, variables);
+ expectedExternalAudit.setRESOURCE_NAME(component.getName());
+ expectedExternalAudit.setRESOURCE_TYPE(component.getComponentType().getValue());
expectedExternalAudit.setARTIFACT_DATA(null);
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentResourceInstanceDetails != null) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getComponentInstances().get(0).getNormalizedName());
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + component.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
+ expectedExternalAudit.setRESOURCE_NAME(component.getComponentInstances().get(0).getNormalizedName());
} else {
if(includeResourceNameInAudit) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
} else {
if((lifeCycleStatesEnum == LifeCycleStatesEnum.CHECKIN) || (lifeCycleStatesEnum == LifeCycleStatesEnum.STARTCERTIFICATION)) {
expectedExternalAudit.setRESOURCE_NAME("");
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, "");
} else {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
}
}
}
@@ -1085,14 +1085,14 @@ public class CRUDExternalAPI extends ComponentBaseTest {
- protected RestResponse uploadArtifactWithInvalidCheckSumOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
+ protected RestResponse uploadArtifactWithInvalidCheckSumOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails,
Integer expectedResponseCode, ComponentInstance componentResourceInstanceDetails, ErrorInfo errorInfo, List<String> variables) throws Exception {
RestResponse restResponse;
if(componentResourceInstanceDetails != null) {
- restResponse = ArtifactRestUtils.externalAPIUploadArtifactWithInvalidCheckSumOfComponentInstanceOnAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails);
+ restResponse = ArtifactRestUtils.externalAPIUploadArtifactWithInvalidCheckSumOfComponentInstanceOnAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, componentResourceInstanceDetails);
} else {
- restResponse = ArtifactRestUtils.externalAPIUploadArtifactWithInvalidCheckSumOfTheAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails);
+ restResponse = ArtifactRestUtils.externalAPIUploadArtifactWithInvalidCheckSumOfTheAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails);
}
@@ -1109,23 +1109,23 @@ public class CRUDExternalAPI extends ComponentBaseTest {
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
// ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
responseArtifact.setUpdaterFullName("");
responseArtifact.setUserIdLastUpdater(sdncModifierDetails.getUserId());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, resourceDetails.getUUID(), errorInfo, variables);
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- expectedExternalAudit.setRESOURCE_TYPE(resourceDetails.getComponentType().getValue());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, component.getUUID(), errorInfo, variables);
+ expectedExternalAudit.setRESOURCE_NAME(component.getName());
+ expectedExternalAudit.setRESOURCE_TYPE(component.getComponentType().getValue());
expectedExternalAudit.setARTIFACT_DATA(null);
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentResourceInstanceDetails != null) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getComponentInstances().get(0).getNormalizedName());
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + component.getComponentInstances().get(0).getNormalizedName() + "/artifacts");
+ expectedExternalAudit.setRESOURCE_NAME(component.getComponentInstances().get(0).getNormalizedName());
} else {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
}
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), body);
@@ -1542,7 +1542,6 @@ 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 {
@@ -1571,10 +1570,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
-
-
-
-
@DataProvider(name="updateArtifactOnRIViaExternalAPI", parallel=true)
public static Object[][] dataProviderUpdateArtifactOnRIViaExternalAPI() {
return new Object[][] {
@@ -1602,10 +1597,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
};
}
-
-
-
-
@Test(dataProvider="updateArtifactOnRIViaExternalAPI")
public void updateArtifactOnRIViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, String artifactType, ResourceTypeEnum resourceTypeEnum) throws Exception {
getExtendTest().log(Status.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType));
@@ -1619,12 +1610,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
}
-
-
-
-
-
-
@DataProvider(name="updateArtifactOnVfcVlCpRIViaExternalAPI", parallel=true)
public static Object[][] dataProviderUpdateArtifactOnVfcVlCpRIViaExternalAPI() {
return new Object[][] {
@@ -1714,10 +1699,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
};
}
-
-
-
-
@Test(dataProvider="updateArtifactOnVfcVlCpRIViaExternalAPI")
public void updateArtifactOnVfcVlCpRIViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, String artifactType, ResourceTypeEnum resourceTypeEnum) throws Exception {
getExtendTest().log(Status.INFO, String.format("chosenLifeCycleState: %s, artifactType: %s", chosenLifeCycleState, artifactType));
@@ -1732,15 +1713,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
}
-
-
-
-
-
-
-
-
-
@DataProvider(name="updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset", parallel=true)
public static Object[][] dataProviderUpdateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset() {
return new Object[][] {
@@ -1789,8 +1761,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
};
}
-
-
// External API
// Update artifact by diffrent user then creator of asset - Fail
@Test(dataProvider="updateArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset")
@@ -1812,8 +1782,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
};
}
-
-
// External API
// Upload artifact on VF via external API - happy flow
@Test(dataProvider="updateArtifactOnAssetWhichNotExist")
@@ -1875,7 +1843,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
};
}
-
@Test(dataProvider="updateArtifactOnAssetWhichInInvalidStateForUploading")
public void updateArtifactOnAssetWhichInInvalidStateForUploading(ComponentTypeEnum componentTypeEnum, String artifactType) throws Exception {
getExtendTest().log(Status.INFO, String.format("componentTypeEnum: %s, artifactType: %s", componentTypeEnum, artifactType));
@@ -2065,10 +2032,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
@@ -2100,10 +2067,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
@@ -2135,10 +2102,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
@@ -2170,10 +2137,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
@@ -2205,10 +2172,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
@@ -2241,21 +2208,14 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentInstance != null) {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
} else {
updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 400, null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, artifactReqDetails, artifactUUID, errorInfo, variables, null, true);
}
}
-
-
-
-
-
-
-
// Unhappy flow - get chosen life cycle state, artifact type and asset type
// update artifact via external API + check audit & response code
@@ -2305,14 +2265,14 @@ public class CRUDExternalAPI extends ComponentBaseTest {
return component;
}
- protected RestResponse updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails,
+ 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 {
RestResponse restResponse;
if(componentInstance != null) {
- restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfComponentInstanceOnAsset(resourceDetails, sdncModifierDetails, artifactReqDetails, componentInstance, artifactUUID);
+ restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfComponentInstanceOnAsset(component, sdncModifierDetails, artifactReqDetails, componentInstance, artifactUUID);
} else {
- restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfTheAsset(resourceDetails, sdncModifierDetails, artifactReqDetails, artifactUUID);
+ restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfTheAsset(component, sdncModifierDetails, artifactReqDetails, artifactUUID);
}
@@ -2326,35 +2286,35 @@ public class CRUDExternalAPI extends ComponentBaseTest {
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPDATE_BY_API;
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
// ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
responseArtifact.setUpdaterFullName("");
responseArtifact.setUserIdLastUpdater(sdncModifierDetails.getUserId());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, resourceDetails.getUUID(), errorInfo, variables);
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- expectedExternalAudit.setRESOURCE_TYPE(resourceDetails.getComponentType().getValue());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, component.getUUID(), errorInfo, variables);
+ expectedExternalAudit.setRESOURCE_NAME(component.getName());
+ expectedExternalAudit.setRESOURCE_TYPE(component.getComponentType().getValue());
expectedExternalAudit.setARTIFACT_DATA("");
expectedExternalAudit.setCURR_ARTIFACT_UUID(artifactUUID);
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentInstance != null) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getComponentInstances().get(0).getNormalizedName());
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + component.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_NAME(component.getComponentInstances().get(0).getNormalizedName());
} else {
expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL() + "/" + artifactUUID);
if((lifeCycleStatesEnum == LifeCycleStatesEnum.CHECKIN) || (lifeCycleStatesEnum == LifeCycleStatesEnum.STARTCERTIFICATION)) {
if(resourceNameInAudit) {
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ expectedExternalAudit.setRESOURCE_NAME(component.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
} else {
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL());
// body.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifactUUID);
expectedExternalAudit.setRESOURCE_NAME("");
}
} else {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
}
}
@@ -2381,7 +2341,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
return downloadResourceDeploymentArtifactExternalAPI(component, component.getDeploymentArtifacts().get(artifactName), sdncModifierDetails, artifactReqDetails, componentTypeEnum);
}
- // Get deployment artifact of asset
+ // Get deployment artifact of RI
protected Map<String, ArtifactDefinition> getDeploymentArtifactsOfAsset(Component component, ComponentTypeEnum componentTypeEnum) {
Map<String, ArtifactDefinition> deploymentArtifacts = null;
if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) {
@@ -2447,20 +2407,13 @@ public class CRUDExternalAPI extends ComponentBaseTest {
deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum);
numberOfArtifact = deploymentArtifacts.size();
-
// create component/s & upload artifact via external api
if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) {
- if((chosenLifeCycleState == LifeCycleStatesEnum.CERTIFICATIONREQUEST) && (!component.getComponentType().toString().equals(ComponentTypeEnum.RESOURCE.toString()))) {
- numberOfArtifact = numberOfArtifact - 1;
- }
restResponse = updateArtifactOfRIIncludingValiditionOfAuditAndResponseCode(component, component.getComponentInstances().get(0), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, artifactUUID, 200);
} else {
-
restResponse = updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, artifactUUID, 200);
}
-
-
ArtifactDefinition responseArtifact = getArtifactDataFromJson(restResponse.getResponse());
component = getNewerVersionOfComponent(component, chosenLifeCycleState);
@@ -2483,8 +2436,8 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// Update artifact via external API + Check auditing for upload operation + Check response of external API
- protected RestResponse updateArtifactOfRIIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, ComponentInstance componentInstance, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
- RestResponse restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfComponentInstanceOnAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, resourceDetails.getComponentInstances().get(0), artifactUUID);
+ protected RestResponse updateArtifactOfRIIncludingValiditionOfAuditAndResponseCode(Component component, ComponentInstance componentInstance, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
+ RestResponse restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfComponentInstanceOnAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, component.getComponentInstances().get(0), artifactUUID);
// Check response of external API
Integer responseCode = restResponse.getErrorCode();
@@ -2499,11 +2452,11 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentInstance.getNormalizedName());
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
// expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body);
return restResponse;
@@ -2511,8 +2464,8 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// Update artifact via external API + Check auditing for upload operation + Check response of external API
- protected RestResponse updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
- RestResponse restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfTheAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, artifactUUID);
+ protected RestResponse updateArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails, ArtifactReqDetails artifactReqDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
+ RestResponse restResponse = ArtifactRestUtils.externalAPIUpdateArtifactOfTheAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails, artifactUUID);
// Check response of external API
Integer responseCode = restResponse.getErrorCode();
@@ -2525,10 +2478,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPDATE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_UPDATE_BY_API.getName(), body);
@@ -2571,9 +2524,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
};
}
-
-
-
// Delete artifact for Service - Success
@Test(dataProvider="deleteArtifactForServiceViaExternalAPI")
public void deleteArtifactForServiceViaExternalAPI(LifeCycleStatesEnum lifeCycleStatesEnum, String artifactType) throws Exception {
@@ -2935,7 +2885,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
// External API
- // Delete artifact by diffrent user then creator of asset - Fail
+ // Delete artifact by different user then creator of asset - Fail
@Test(dataProvider="deleteArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset")
public void deleteArtifactOnVFViaExternalAPIByDiffrentUserThenCreatorOfAsset(ComponentTypeEnum componentTypeEnum, UserRoleEnum userRoleEnum, LifeCycleStatesEnum lifeCycleStatesEnum, String artifactType) throws Exception {
getExtendTest().log(Status.INFO, String.format("componentTypeEnum: %s, userRoleEnum %s, lifeCycleStatesEnum %s, artifactType: %s", componentTypeEnum, userRoleEnum, lifeCycleStatesEnum, artifactType));
@@ -2955,10 +2905,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum),
- 409, component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, lifeCycleStatesEnum, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, lifeCycleStatesEnum, true);
} else {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(userRoleEnum),
- 409, null, artifactUUID, errorInfo, variables, lifeCycleStatesEnum, true);
+ errorInfo.getCode(), null, artifactUUID, errorInfo, variables, lifeCycleStatesEnum, true);
}
//TODO
@@ -3000,10 +2950,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, component.getComponentInstances().get(0), invalidArtifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), invalidArtifactUUID, errorInfo, variables, null, true);
} else {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, null, invalidArtifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, invalidArtifactUUID, errorInfo, variables, null, true);
}
@@ -3014,7 +2964,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),
- 404, component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, true);
} else {
component.setUUID("invalidComponentUUID");
if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE)) {
@@ -3024,7 +2974,7 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
variables = asList("invalidComponentUUID");
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, null, artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, false);
+ errorInfo.getCode(), null, artifactUUID, errorInfo, variables, LifeCycleStatesEnum.CHECKIN, false);
}
@@ -3065,10 +3015,10 @@ public class CRUDExternalAPI extends ComponentBaseTest {
if(componentTypeEnum.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 403, component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null, true);
} else {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 403, null, artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), null, artifactUUID, errorInfo, variables, null, true);
}
@@ -3110,17 +3060,17 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
List<String> variables = asList(artifactUUID);
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
- 404, component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null, true);
+ errorInfo.getCode(), component.getComponentInstances().get(0), artifactUUID, errorInfo, variables, null, true);
}
- protected RestResponse deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails,
+ protected RestResponse deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails,
Integer expectedResponseCode, ComponentInstance componentInstance, String artifactUUID, ErrorInfo errorInfo, List<String> variables, LifeCycleStatesEnum lifeCycleStatesEnum, Boolean resourceNameInAudit) throws Exception {
RestResponse restResponse;
if(componentInstance != null) {
- restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfComponentInstanceOnAsset(resourceDetails, sdncModifierDetails, componentInstance, artifactUUID);
+ restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfComponentInstanceOnAsset(component, sdncModifierDetails, componentInstance, artifactUUID);
} else {
- restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfTheAsset(resourceDetails, sdncModifierDetails, artifactUUID);
+ restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfTheAsset(component, sdncModifierDetails, artifactUUID);
}
@@ -3133,37 +3083,37 @@ public class CRUDExternalAPI extends ComponentBaseTest {
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_DELETE_BY_API;
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
// ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
responseArtifact.setUpdaterFullName("");
responseArtifact.setUserIdLastUpdater(sdncModifierDetails.getUserId());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, resourceDetails.getUUID(), errorInfo, variables);
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- expectedExternalAudit.setRESOURCE_TYPE(resourceDetails.getComponentType().getValue());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditFailure(assetTypeEnum, action, responseArtifact, component.getUUID(), errorInfo, variables);
+ expectedExternalAudit.setRESOURCE_NAME(component.getName());
+ expectedExternalAudit.setRESOURCE_TYPE(component.getComponentType().getValue());
expectedExternalAudit.setARTIFACT_DATA(null);
expectedExternalAudit.setCURR_ARTIFACT_UUID(artifactUUID);
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_STATUS, responseCode.toString());
if(componentInstance != null) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getComponentInstances().get(0).getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + resourceDetails.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getComponentInstances().get(0).getNormalizedName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getComponentInstances().get(0).getNormalizedName());
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + component.getComponentInstances().get(0).getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_NAME(component.getComponentInstances().get(0).getNormalizedName());
} else {
expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL() + "/" + artifactUUID);
if((errorInfo.getMessageId().equals(ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESOURCE_NOT_FOUND.name()).getMessageId())) ||
errorInfo.getMessageId().equals(ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name()).getMessageId()) ||
(lifeCycleStatesEnum == LifeCycleStatesEnum.STARTCERTIFICATION)) {
if(resourceNameInAudit) {
- expectedExternalAudit.setRESOURCE_NAME(resourceDetails.getName());
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ expectedExternalAudit.setRESOURCE_NAME(component.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
} else {
expectedExternalAudit.setRESOURCE_NAME("");
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL());
}
} else {
if(resourceNameInAudit) {
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
} else {
expectedExternalAudit.setRESOURCE_NAME("");
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_URL, expectedExternalAudit.getRESOURCE_URL());
@@ -3185,7 +3135,11 @@ public class CRUDExternalAPI extends ComponentBaseTest {
protected Component deleteArtifactOnAssetViaExternalAPI(Component component, ComponentTypeEnum componentTypeEnum, LifeCycleStatesEnum chosenLifeCycleState) throws Exception {
String artifactName = null;
component = AtomicOperationUtils.changeComponentState(component, UserRoleEnum.DESIGNER, chosenLifeCycleState, true).getLeft();
-
+ if(!LifeCycleStatesEnum.CHECKOUT.equals(chosenLifeCycleState)){
+ component = AtomicOperationUtils.getComponentObject(component, UserRoleEnum.DESIGNER);
+ }else{
+ component = getNewerVersionOfComponent(component, chosenLifeCycleState);
+ }
// get updated artifact data
String artifactUUID = null;
int moduleTypeArtifact = 0;
@@ -3202,12 +3156,9 @@ public class CRUDExternalAPI extends ComponentBaseTest {
break;
}
}
-
String componentVersionBeforeDelete = component.getVersion();
int numberOfArtifact = deploymentArtifacts.size();
-
-
// create component/s & upload artifact via external api
if(ComponentTypeEnum.RESOURCE_INSTANCE == componentTypeEnum) {
@@ -3215,8 +3166,8 @@ public class CRUDExternalAPI extends ComponentBaseTest {
} else {
deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactUUID, 200);
}
-
- component = getNewerVersionOfComponent(component, chosenLifeCycleState);
+
+ component = updateComponentDetailsByLifeCycleState(chosenLifeCycleState, component);
// Get list of deployment artifact + download them via external API
deploymentArtifacts = getDeploymentArtifactsOfAsset(component, componentTypeEnum);
@@ -3228,7 +3179,6 @@ public class CRUDExternalAPI extends ComponentBaseTest {
} else {
Assert.assertEquals(numberOfArtifact - 1, deploymentArtifacts.keySet().size(), "Expected that number of deployment artifact will decrease by one.");
}
-
if(chosenLifeCycleState == LifeCycleStatesEnum.CHECKOUT) {
Assert.assertEquals(componentVersionBeforeDelete, component.getVersion(), "Expected that check-out component will not change version number.");
@@ -3242,8 +3192,8 @@ public class CRUDExternalAPI extends ComponentBaseTest {
}
// Delete artifact via external API + Check auditing for upload operation + Check response of external API
- protected RestResponse deleteArtifactOfRIIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, ComponentInstance componentInstance, User sdncModifierDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
- RestResponse restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfComponentInstanceOnAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getComponentInstances().get(0), artifactUUID);
+ protected RestResponse deleteArtifactOfRIIncludingValiditionOfAuditAndResponseCode(Component component, ComponentInstance componentInstance, User sdncModifierDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
+ RestResponse restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfComponentInstanceOnAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), component.getComponentInstances().get(0), artifactUUID);
// Check response of external API
Integer responseCode = restResponse.getErrorCode();
@@ -3258,20 +3208,20 @@ public class CRUDExternalAPI extends ComponentBaseTest {
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentInstance.getNormalizedName());
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
// expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
expectedExternalAudit.setRESOURCE_NAME(componentInstance.getNormalizedName());
- expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + resourceDetails.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
+ expectedExternalAudit.setRESOURCE_URL("/sdc/v1/catalog/" + assetTypeEnum.getValue() + "/" + component.getUUID() + "/resourceInstances/" + componentInstance.getNormalizedName() + "/artifacts/" + artifactUUID);
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), body);
-
+ component = AtomicOperationUtils.getComponentObject(component, UserRoleEnum.DESIGNER);
return restResponse;
}
// Delete artifact via external API + Check auditing for upload operation + Check response of external API
- protected RestResponse deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component resourceDetails, User sdncModifierDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
- RestResponse restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfTheAsset(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactUUID);
+ protected RestResponse deleteArtifactOfAssetIncludingValiditionOfAuditAndResponseCode(Component component, User sdncModifierDetails, String artifactUUID, Integer expectedResponseCode) throws Exception {
+ RestResponse restResponse = ArtifactRestUtils.externalAPIDeleteArtifactOfTheAsset(component, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactUUID);
// Check response of external API
Integer responseCode = restResponse.getErrorCode();
@@ -3284,26 +3234,26 @@ public class CRUDExternalAPI extends ComponentBaseTest {
AuditingActionEnum action = AuditingActionEnum.ARTIFACT_DELETE_BY_API;
Map <AuditingFieldsKeysEnum, String> body = new HashMap<>();
- body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceDetails.getName());
+ body.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
- AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((resourceDetails.getComponentType().getValue() + "s").toUpperCase());
- ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, resourceDetails);
+ AssetTypeEnum assetTypeEnum = AssetTypeEnum.valueOf((component.getComponentType().getValue() + "s").toUpperCase());
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(assetTypeEnum, action, responseArtifact, component);
expectedExternalAudit.setRESOURCE_URL(expectedExternalAudit.getRESOURCE_URL()+ "/" + artifactUUID);
AuditValidationUtils.validateExternalAudit(expectedExternalAudit, AuditingActionEnum.ARTIFACT_DELETE_BY_API.getName(), body);
-
+ component = AtomicOperationUtils.getComponentObject(component, UserRoleEnum.DESIGNER);
return restResponse;
}
// download deployment via external api + check response code for success (200) + get artifactReqDetails and verify payload + verify audit
- protected RestResponse downloadResourceDeploymentArtifactExternalAPI(Component resourceDetails, User sdncModifierDetails, String artifactUUID, ComponentTypeEnum componentTypeEnum) throws Exception {
+ protected RestResponse downloadResourceDeploymentArtifactExternalAPI(Component component, User sdncModifierDetails, String artifactUUID, ComponentTypeEnum componentTypeEnum) throws Exception {
RestResponse restResponse;
if(componentTypeEnum == ComponentTypeEnum.RESOURCE_INSTANCE) {
- restResponse = ArtifactRestUtils.getComponentInstanceDeploymentArtifactExternalAPI(resourceDetails.getUUID(), resourceDetails.getComponentInstances().get(0).getNormalizedName(), artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getComponentType().toString());
+ restResponse = ArtifactRestUtils.getComponentInstanceDeploymentArtifactExternalAPI(component.getUUID(), component.getComponentInstances().get(0).getNormalizedName(), artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), component.getComponentType().toString());
} else {
- restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceDetails.getUUID(), artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getComponentType().toString());
+ restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(component.getUUID(), artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), component.getComponentType().toString());
}
Integer responseCode = restResponse.getErrorCode();
diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetCSARofVF.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetCSARofVF.java
index 6acc54b54c..9d56316b18 100644
--- a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetCSARofVF.java
+++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/GetCSARofVF.java
@@ -20,11 +20,10 @@
package org.openecomp.sdc.externalApis;
-import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
import java.io.File;
import java.io.IOException;
-import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
@@ -34,58 +33,27 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.io.IOUtils;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Rule;
import org.junit.rules.TestName;
-import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
-import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
import org.openecomp.sdc.be.model.Component;
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.resources.data.auditing.AuditingActionEnum;
import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
-import org.openecomp.sdc.ci.tests.api.Urls;
-import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure;
-import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceAssetStructure;
-import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedExternalAudit;
-import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
-import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
-import org.openecomp.sdc.ci.tests.utils.Utils;
-import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils;
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.AssetRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
-import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
-import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
-import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import static org.testng.AssertJUnit.assertTrue;
-
-import com.google.gson.Gson;
-
-import fj.data.Either;
public class GetCSARofVF extends ComponentBaseTest {
@@ -224,22 +192,42 @@ public class GetCSARofVF extends ComponentBaseTest {
}
-
-
-
-
+ /**
+ * all files in list(expectedDefinitionFolderFileList) must be found in csar file
+ * @param resource
+ * @param toscaModelCsarFile
+ * @throws ZipException
+ * @throws IOException
+ */
public void validateCsarContent(Component resource, File toscaModelCsarFile) throws ZipException, IOException {
ZipFile zipFile = new ZipFile(toscaModelCsarFile);
+ List<String> expectedDefinitionFolderFileList = new ArrayList<String>();
+ expectedDefinitionFolderFileList.add("Definitions/"+ resource.getComponentType().getValue().toLowerCase()+"-"+ resource.getSystemName()+"-template.yml");
+ expectedDefinitionFolderFileList.add("Definitions/"+ resource.getComponentType().getValue().toLowerCase()+"-"+ resource.getSystemName()+"-template-interface.yml");
+ expectedDefinitionFolderFileList.add("Definitions/relationships.yml");
+ expectedDefinitionFolderFileList.add("Definitions/policies.yml");
+ expectedDefinitionFolderFileList.add("Definitions/nodes.yml");
+ expectedDefinitionFolderFileList.add("Definitions/interfaces.yml");
+ expectedDefinitionFolderFileList.add("Definitions/groups.yml");
+ expectedDefinitionFolderFileList.add("Definitions/data.yml");
+ expectedDefinitionFolderFileList.add("Definitions/capabilities.yml");
+ expectedDefinitionFolderFileList.add("Definitions/artifacts.yml");
+
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while(entries.hasMoreElements()){
ZipEntry nextElement = entries.nextElement();
if (!(nextElement.getName().contains("Artifacts")||nextElement.getName().contains("csar.meta"))){
- assertTrue("missing file in csar template", (nextElement.getName().equals("TOSCA-Metadata/TOSCA.meta") ||
- nextElement.getName().equals("Definitions/"+ resource.getComponentType().getValue().toLowerCase()+"-"+ resource.getSystemName()+"-template.yml")) ||
- nextElement.getName().equals("Definitions/"+ resource.getComponentType().getValue().toLowerCase()+"-"+ resource.getSystemName()+"-template-interface.yml"));
+// assertTrue("missing file in csar template", (nextElement.getName().equals("TOSCA-Metadata/TOSCA.meta") ||
+// nextElement.getName().equals("Definitions/"+ resource.getComponentType().getValue().toLowerCase()+"-"+ resource.getSystemName()+"-template.yml")) ||
+// nextElement.getName().equals("Definitions/"+ resource.getComponentType().getValue().toLowerCase()+"-"+ resource.getSystemName()+"-template-interface.yml"));
+ if(expectedDefinitionFolderFileList.contains(nextElement.getName())){
+ expectedDefinitionFolderFileList.remove(nextElement.getName());
}
}
+ }
+ zipFile.close();
+ assertTrue("missing files in csar template definitions folder", expectedDefinitionFolderFileList.size() == 0);
}
public void validateAudit(Component resource) throws Exception {
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 f93958542d..6e212d3155 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
@@ -216,10 +216,10 @@ 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,21 +272,21 @@ public class VFCMTExternalAPI extends ComponentBaseTest {
case "description_with_invalid_char":
defaultResource.setDescription("\uC2B5");
expectedResourceAuditJavaObject.setDesc("t");
- errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_INVALID_DESCRIPTION.name());
+ errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_RESOURCE_TYPE.name());
variables = asList(ComponentTypeEnum.RESOURCE.getValue());
break;
// TODO: defect on the flow - need to get error instead create VFC
case "resource_type_missing":
defaultResource.setResourceType("");
expectedResourceAuditJavaObject.setResourceType("");
- errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name());
+ errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT.name());
variables = asList(ComponentTypeEnum.RESOURCE.getValue());
break;
// TODO: in audit RESOURCE_NAME is empty
case "resource_type_invalid":
defaultResource.setResourceType("invalid");
expectedResourceAuditJavaObject.setResourceType(ComponentTypeEnum.RESOURCE.getValue());
- errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT.name());
+ errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_RESOURCE_TYPE.name());
variables = asList(ComponentTypeEnum.RESOURCE.getValue());
break;
case "category_type_missing":
@@ -377,7 +377,7 @@ public class VFCMTExternalAPI extends ComponentBaseTest {
// create vfcmt
RestResponse restResponse = ResourceRestUtilsExternalAPI.createResource(defaultResource, defaultUser);
- expectedResourceAuditJavaObject.setStatus("400");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
AuditValidationUtils.validateAuditExternalCreateResource(expectedResourceAuditJavaObject, action.getName(), body);
diff --git a/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml b/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml
index 7273344672..10402eb2b0 100644
--- a/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml
+++ b/test-apis-ci/src/main/resources/ci/conf/attsdc.yaml
@@ -1,6 +1,6 @@
outputFolder: target
reportName: index.html
-catalogBeHost: behost
+catalogBeHost: localhost
catalogFeHost: fehost
esHost: eshost
disributionClientHost: disClient
diff --git a/test-apis-ci/src/test/resources/CI/error-configuration.yaml b/test-apis-ci/src/test/resources/CI/error-configuration.yaml
index ef7a885678..899a225152 100644
--- a/test-apis-ci/src/test/resources/CI/error-configuration.yaml
+++ b/test-apis-ci/src/test/resources/CI/error-configuration.yaml
@@ -1776,3 +1776,9 @@ errors:
message: "Creation of %1 failed. Generic type %2 was not found",
messageId: "SVC4660"
}
+ #---------SVC4669-----------------------------
+ INVALID_RESOURCE_TYPE: {
+ code: 400,
+ message: "Error: Invalid resource type.",
+ messageId: "SVC4669"
+ } \ No newline at end of file
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MIBsArtifactsOnResourceInstance.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MIBsArtifactsOnResourceInstance.java
index 949a20b4a9..4e4192fe7e 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MIBsArtifactsOnResourceInstance.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/US/MIBsArtifactsOnResourceInstance.java
@@ -78,10 +78,6 @@ public class MIBsArtifactsOnResourceInstance extends SetupCDTest {
setLog("mibsArtifactCRUDUi");
String filePath = FileHandling.getFilePath(folder);
- if(true){
- throw new SkipException("Open bug 197101");
- }
-
// import Resource
ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(resourceTypeEnum, getUser());
ResourceUIUtils.importVfc(resourceMetaData, filePath, fileName, getUser());
diff --git a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java
index ef510b8a12..5bbc8ad9e0 100644
--- a/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java
+++ b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/DataTestIdEnum.java
@@ -433,19 +433,19 @@ public final class DataTestIdEnum {
}
public enum StepsEnum {
- GENERAL("Generalstep"),
+ GENERAL("General"),
ICON("Iconstep"),
- DEPLOYMENT_ARTIFACT("Deployment Artifactstep"),
- INFORMATION_ARTIFACT("Information Artifactstep"),
- PROPERTIES("Propertiesstep"),
- COMPOSITION("Compositionstep"),
- ACTIVITY_LOG("Activity Logstep"),
- DEPLOYMENT_VIEW("Deploymentstep"),
- TOSCA_ARTIFACTS("TOSCA Artifactsstep"),
+ DEPLOYMENT_ARTIFACT("Deployment Artifact"),
+ INFORMATION_ARTIFACT("Information Artifact"),
+ PROPERTIES("Properties"),
+ COMPOSITION("Composition"),
+ ACTIVITY_LOG("Activity Log"),
+ DEPLOYMENT_VIEW("Deployment"),
+ TOSCA_ARTIFACTS("TOSCA Artifacts"),
MONITOR("Monitor step"),
- MANAGEMENT_WORKFLOW("Management Workflowstep"),
- INPUTS("Inputsstep"),
- HIERARCHY("Hierarchystep");
+ MANAGEMENT_WORKFLOW("Management Workflow"),
+ INPUTS("Inputs"),
+ HIERARCHY("Hierarchy");
private String value;
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 fddb97ace3..76723bba11 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
@@ -27,9 +27,11 @@ import java.awt.AWTException;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Random;
import java.util.stream.Collectors;
import org.openecomp.sdc.ci.tests.datatypes.CanvasElement;
@@ -94,6 +96,36 @@ public class Onboard extends SetupCDTest {
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);
+ }
+
+
+ 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")) {
@@ -116,6 +148,7 @@ public class Onboard extends SetupCDTest {
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;
@@ -193,6 +226,14 @@ public class Onboard extends SetupCDTest {
runOnboardToDistributionFlow(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);
+ runOnboardToDistributionFlow(filepath, vnfFile);
+ }
+
@Test
public void onboardUpdateVNFTest() throws Exception, Throwable {
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 cb647aec6d..0dc6740c30 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
@@ -25,6 +25,7 @@ import static org.testng.AssertJUnit.assertEquals;
import java.awt.AWTException;
import java.io.File;
import java.io.FileOutputStream;
+import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.ArrayList;
@@ -40,6 +41,7 @@ import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.Service;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceDistributionStatus;
import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
@@ -49,6 +51,8 @@ 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.ResourceRestUtils;
import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.tosca.parser.exceptions.SdcToscaParserException;
+import org.openecomp.sdc.toscaparser.api.common.JToscaException;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
@@ -125,6 +129,34 @@ public class OnboardViaApis{
}
+
+ @Test
+ public void onboardingAndParser() throws Exception {
+ Service service = null;
+ String filepath = getFilePath();
+ Object[] fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath);
+ String vnfFile = fileNamesFromFolder[7].toString();
+ System.err.println(timestamp + " Starting test with VNF: " + vnfFile);
+ service = runOnboardViaApisOnly(filepath, vnfFile);
+
+// AtomicOperationUtils.getServiceObjectByNameAndVersion(sdncModifierDetails, serviceName, serviceVersion);
+// RestResponse distributeService = AtomicOperationUtils.distributeService(service, true);
+// Map<Long, ServiceDistributionStatus> convertServiceDistributionStatusToObject = ResponseParser.convertServiceDistributionStatusToObject(distributeService.getResponse());
+// convertServiceDistributionStatusToObject.
+ }
+
+ 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 void downloadToscaCsarToDirectory(Service service, File file) {
try {
Either<String,RestResponse> serviceToscaArtifactPayload = AtomicOperationUtils.getServiceToscaArtifactPayload(service, "assettoscacsar");
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 d5920a22ca..3a42d22d0e 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
@@ -387,10 +387,6 @@ public class Service extends SetupCDTest {
@Test
public void deleteDeploymentArtifactFromVFInstanceTest() throws Exception{
- if(true){
- throw new SkipException("Open bug 300513");
- }
-
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());
@@ -405,10 +401,6 @@ public class Service extends SetupCDTest {
@Test
public void deleteDeploymentArtifactFromVFInstanceNextVersionTest() throws Exception{
- if(true){
- throw new SkipException("Open bug 300513");
- }
-
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());
@@ -434,10 +426,6 @@ public class Service extends SetupCDTest {
@Test
public void updateDeploymentArtifactOnVFInstanceNextVersionTest() throws Exception{
- if(true){
- throw new SkipException("Open bug 300513");
- }
-
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/Vf.java b/ui-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/sanity/Vf.java
index a94a63500d..ef7a534ee9 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
@@ -231,10 +231,6 @@ public class Vf extends SetupCDTest {
@Test
public void addPropertiesToVfcInstanceInVfTest() throws Exception {
- if(true){
- throw new SkipException("Open bug 292047");
- }
-
String fileName = "vFW_VFC.yml";
ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser());
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 621cc26a12..ae05e77aff 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
@@ -506,6 +506,7 @@ public class OnboardingUtils {
jObject.put("description", "new VSP description");
jObject.put("category", "resourceNewCategory.generic");
jObject.put("subCategory", "resourceNewCategory.generic.database");
+ jObject.put("onboardingMethod", "HEAT");
jObject.put("licensingVersion", jlicensingVersionObj);
jObject.put("vendorName", vendorName);
jObject.put("vendorId", vendorId);
@@ -669,7 +670,7 @@ public class OnboardingUtils {
boolean vspFound = HomePage.searchForVSP(vspName);
if (vspFound){
-
+
List<WebElement> elemenetsFromTable = HomePage.getElemenetsFromTable();
// WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30);
// WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1)));
@@ -767,24 +768,36 @@ public class OnboardingUtils {
LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = ((LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get("Deployment"));
ArtifactsCorrelationManager.addVNFartifactDetails(vspName, deploymentArtifacts);
- validateDeploymentArtifactsVersion(deploymentArtifacts);
+ List<String> heatEnvFilesFromCSAR = deploymentArtifacts.stream().filter(e -> e.getType().equals("HEAT_ENV")).
+ map(e -> e.getFileName()).
+ collect(Collectors.toList());
+
+ validateDeploymentArtifactsVersion(deploymentArtifacts, heatEnvFilesFromCSAR);
+
DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile);
return createVendorSoftwareProduct;
}
- public static void validateDeploymentArtifactsVersion(LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts) {
- String artifactVersion = "1";
+ public static void validateDeploymentArtifactsVersion(LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts,
+ List<String> heatEnvFilesFromCSAR) {
+ String artifactVersion;
String artifactName;
-
+
for(HeatMetaFirstLevelDefinition deploymentArtifact: deploymentArtifacts) {
+ artifactVersion = "1";
+
if(deploymentArtifact.getType().equals("HEAT_ENV")) {
continue;
} else if(deploymentArtifact.getFileName().contains(".")) {
- artifactName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf("."));
+ artifactName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf("."));
} else {
- artifactName = deploymentArtifact.getFileName().trim();
+ artifactName = deploymentArtifact.getFileName().trim();
+ }
+
+ if (heatEnvFilesFromCSAR.contains(artifactName + ".env")){
+ artifactVersion = "2";
}
- ArtifactUIUtils.validateArtifactNameVersionType(artifactName, artifactVersion, deploymentArtifact.getType());
+ ArtifactUIUtils.validateArtifactNameVersionType(artifactName, artifactVersion, deploymentArtifact.getType());
}
}